Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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
 /var/tmp/test.txt
 [root@om-1 tmp]# echo $?
                  0
 [root@om-1 tmp]# find /var/tmp -name  test1.txt (test1.txt not under /var/tmp)
 [root@om-1 tmp]# echo $?
                  0
share|improve this question

4 Answers 4

up vote 2 down vote accepted

You can't.

From the find man page:

 EXIT STATUS
        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` 
ECHO $COUNT
0
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 :) –  SvW Jan 10 '12 at 13:24

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
1  
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

 
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.