Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

when I perform

  find /tmp  -name something 

find command not find the something word under /tmp

  echo $?

  I get $?=0

it's OK

but how to enable Exit status diff then 0 when find command not find the something word?

share|improve this question
    
Please don't cross-post. –  Dennis Williamson Jan 23 '11 at 17:14

2 Answers 2

up vote 1 down vote accepted

find returns 0 if it runs successfully and non-zero if there are errors. It does not set the exit code based on whether anything was found. You will need to do something like this:

files=$(find /tmp  -name something)
if [[ -n "$files" ]]
then
    echo "files were found"
fi

It's more likely, however, that you want to do something with the filenames. You can process them in a loop:

find /tmp  -name something | while read -r filename
do
    echo "found: $filename
done

or

while read -r filename
do
    echo "found: $filename
done < <(find /tmp  -name something)

If nothing is found then the loop will exit without doing anything.

share|improve this answer

I feel that this is the most concise and direct method:

test "`find /tmp/ -name something -print -quit 2>/dev/null`"
share|improve this answer
1  
This will only work if there's not more than a single match. Double quotes around the backticks should overcome this. –  sudo Feb 6 '13 at 19:16
    
Indeed. Fixed. Thanks! –  danorton Feb 7 '13 at 18:02
    
Also, I accidentally omitted -print -quit. –  danorton Feb 7 '13 at 18:19

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.