1

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

5 Answers 5

2

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
1

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

1
  • 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, 2012 at 13:24
1

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
0

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.

0

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.

1
  • 1
    What about test -e /var/tmp/test.txt? This is what the test command is for.
    – f4m8
    Jan 10, 2012 at 14:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .