Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

how to enable find command to print exe status diff from 0 when find command not find the file?

according to my example when I try to find the test1.txt file , $? set to 0 but I expect to get value diff from 0 because the file not found

 [root@om-1 tmp]# touch test.txt
 [root@om-1 tmp]# find /var/tmp -name  test.txt
 [root@om-1 tmp]# echo $?
 [root@om-1 tmp]# find /var/tmp -name  test1.txt (test1.txt not under /var/tmp)
 [root@om-1 tmp]# echo $?
share|improve this question
up vote 2 down vote accepted

You can't.

From the find man page:

        find  exits with status 0 if all files are processed successfully, 
        greater than 0 if errors occur.   This is deliberately
        a very broad description, but if the return value is non-zero, 
        you should not rely on the correctness of the  results  of find.

The exit status 0 just says: I managed to process all files without error (e.g. permission problems).

One solution:

COUNT=`find / -type f -name "thisfiledoesnnotexist" -print | wc -l` 
share|improve this answer

Whereas locate returns 1 when the file is not found in the database

share|improve this answer
locate is often not installed by default, the database might be out of date and it's not nearly as flexible as find. OTOH it's much faster and easier to use :) – Sven Jan 10 '12 at 13:24

Try the following shell condition:

[ "$(find /var/tmp -name test.txt)" ] && echo Found || echo Not found

which is basically the same as:

[ "$(find /var/tmp -name test.txt)" '!=' '' ] && echo Found || echo Not found
share|improve this answer

The exit status of find should be zero in both cases, because the find command did not fail. In case it did not find any match, it just exists normally without printing any output.

As a workaround, you can use something like:

if [ `find . -name test1.txt | grep test1.txt | wc -l` -eq 0 ] ; then echo 1 ; else echo 0; fi

However, I am not sure about the result in case of error.

share|improve this answer

Is using find mandatory for you? Do you exactly know where some file should be? Then for example

stat /var/tmp/test.txt; echo $?
stat /var/tmp/test1.txt; echo $?

should work for you.

share|improve this answer
What about test -e /var/tmp/test.txt? This is what the test command is for. – f4m8 Jan 10 '12 at 14:35

Your Answer


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.