Even when /tmp
has no file called something
, searching for it with find
will return 0:
$ find /tmp -name something
$ echo $?
0
How can I get a non-zero exit status when find
does not find anything?
Even when /tmp
has no file called something
, searching for it with find
will return 0:
$ find /tmp -name something
$ echo $?
0
How can I get a non-zero exit status when find
does not find anything?
The return status will be
0
when something is found, and non-zero otherwise.EDIT: Changed from
egrep '.*'
to the much simplergrep .
, since the result is the same.Exit 0 is easy with find, exit >0 is harder because that usually only happens with an error. However we can make it happen:
Simplest solution that doesn't print, but exits 0 when results found
Having just found this question whilst trying to find my way to solve a problem with Puppet (change permissions on folders under a directory but not on the directory itself), this seems to work:
My specific use case is this:
Which will exit code 1 if the find command finds no files with the required permissions.
It's not possible. Find returns 0 if it exits successfully, even if it didn't find a file (which is a correct result not indicating an error when the file indeed doesn't exist).
To quote the find manpage
Depending on what you want to achieve you could try to let find
-print
the filename and test against it's output:I feel that this is the most concise and direct method:
Here's a little script I called
test.py
. It improves upon other methods posted in that it will return an error code if one is set, and it additionally set one if find didn't list any files:Here's the command-line output:
Then, for a result where find had errors but found files:
Then, if you want the list of files you can make use of
-print 0
passed tofind
and split the out variable on nulls, or you can just add a print statement for it.It is not only
find
that returns the exit status codes as zero when it successful. In unix what ever the command you execute, if its succeeds then it returns the exit status as zero.