How to know if the command find any result?

Posted on

Problem :



for i in `find ./ -name "*jar"`
echo "Looking in $i ..."
grepjar -e $LOOK_FOR $i

I wrote the script above, and try to find if there any file name LOOK_FOR exist in those jar,my quest is:
grepjar -e $LOOK_FOR $i
here how can I check if there are any successful result , and output them ?

by the way, what’s mean of $? in shell script ?
Thanks !

Solution :

Try the following change:



find ./ -name "*.jar" -print | while read -r FILE
echo "Looking in ${FILE} ..."
grepjar -e "${LOOK_FOR}" "${FILE}" 2>/dev/null >/dev/null
if [ ${RETCODE} -eq 0 ]; then
  echo "Found ${LOOK_FOR} in ${FILE}"

The ? variable stores the return value of the last command. This will normally be 0 for success and any other value for failure.

You’ll also notice that I’ve swiched the for command into a while command. That allows for a larger set of returned results.

Breaking down that find ./ -name "*.jar" -print | while read -r FILE command:

find ./ – starting in the current directory…
-name "*.jar" – find files ending in .jar
-print – and print their names
| – redirect that output to the next command
while read -r FILE – and while there is output from the previous command, assign it to the variable FILE and run the commands between do and done.

In other words, it takes the output of the find command (the list of files ending in jar) and runs the block of code in the loop. For a short list it behaves exactly like your version using the for i in loop. The advantage is that it supports long lists, since there’s an upper limit to what you can pass on the command line, as you were doing with the for i in loop.

Edit: Changed to bash script, changed style of variable quoting, included suggestions from comments and some other style changes.

You should be able to use $?.

In bash $? stores the return value of a command. You could check this value after the grepjar command and echo $i if it is what you are after.

Leave a Reply

Your email address will not be published.