Find Command – Make Find Fail When Nothing Found

exit-statusfind

When find is invoked to find nothing, it still exits with code 0. Is there a way to make it return an exit code indicating failure when no file was found?

Best Answer

If your grep supports reading NUL-delimited lines (like GNU grep with -z), you can use it to test if anything was output by find:

find /some/path -print0 | grep -qz .

To pipe the data to another command, you can remove the -q option, letting grep pass on the data unaltered while still reporting an error if nothing came through:

find /some/path -print0 | grep -z . | ...

Specifically, ${PIPESTATUS[1]} in bash should hold the exit status of grep.

If your find doesn't support -print0, the use grep without -z and hope that newlines in filenames don't cause problems:

find ... | grep '^' | ...

In this case, using ^ instead of . might be safer. If output has consecutive newlines, ^ will pass them by, but . won't.