Search code examples
bashfindfile-exists

Test file existence with exit status from gnu-find


When test -e file is not flexible enough, I tend to use the following Bash idiom to check the existence of a file:

if [ -n "$(find ${FIND_ARGS} -print -quit)" ] ; then
   echo "pass"
else
   echo "fail"
fi

But since I am only interested in a boolean value, are there any ${FIND_ARGS} that will let me do instead:

if find ${FIND_ARGS} ; ...

Solution

  • I'd say no. man find...

    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.

    Testing for output is probably fine for find. That isn't a "Bash idiom". If that's not good enough and you have Bash available then you can use extglobs and possibly globstar for file matching tests with [[. Find should only be used for complex recursive file matching, or actual searching for files, and other things that can't easily be done with Bash features.