How to detect whether "find" found any matches?

If you know you have GNU find, use -quit to make it stop after the first match.

Portably, pipe the output of find into head -n 1. That way find will die of a broken pipe after a few matches (when it's filled head's input buffer).

Either way, you don't need wc to test whether a string is empty, the shell can do it on its own.

if [ -n "$(find … | head -n 1)" ]; then …

You can use the -quit action to stop after the first match. You'll probably want to combine that with another action (like -print) or you won't be able to tell whether it found anything.

For example, find ... -print -quit will print the path of the first matching file and then exit. Or, you could use -printf 1 -quit to print 1 if there's a match and nothing if there isn't.

find's exit status reflects whether there were errors while searching, and not whether it found anything, so you have to check its output to see if there's a match.


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 {} +
then
  echo 'nothing found'
else
  echo 'something found'
fi

Note that this solution is more performant than using a subshell; execing false is certainly faster than execing even Dash:

$ cat alfa.sh bravo.sh charlie.sh delta.sh
find -name non-existing-file -exec false {} +
find -name existing-file -exec false {} +
[ "$(find -name non-existing-file)" ]
[ "$(find -name existing-file)" ]

$ strace dash alfa.sh | wc -l
807

$ strace dash bravo.sh | wc -l
1141

$ strace dash charlie.sh | wc -l
1184

$ strace dash delta.sh | wc -l
1194

Tags:

Find

Osx