Can I make `find` return non-0 when no matching files are found?

Solution 1:

find /tmp -name something | grep .

The return status will be 0 when something is found, and non-zero otherwise.

EDIT: Changed from egrep '.*' to the much simpler grep ., since the result is the same.

Solution 2:

Simplest solution that doesn't print, but exits 0 when results found

find /tmp -name something | grep -q "."

Solution 3:

Exit 0 is easy with find, exit >0 is harder because that usually only happens with an error. However we can make it happen:

if find -type f -exec false {} +
  echo 'nothing found'
  echo 'something found'

Solution 4:

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:

test -n "$(find /tmp -name something)"

My specific use case is this:

test -n "$(find /home -mindepth 1 -maxdepth 1 -perm -711)"

Which will exit code 1 if the find command finds no files with the required permissions.

Solution 5:

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


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.

Depending on what you want to achieve you could try to let find -print the filename and test against it's output:

MYVAR=`find . -name "something" -print`
if [ -z "$MYVAR" ]; then
    echo "Notfound"
   echo $MYVAR