1

I would like to use find on a directory structure to exit if at least one file exists with a target condition, because this will lead to a failure of the rest of a shell script.

Since this shell script is intended to run on big directory structures I would like to exit of it as soon as possible.

For example I would like to do:

find . -name "test" -prune
# if "test" file found, just exit immediately
if [ $? -eq 0 ] ; then
    echo error... >&2
    exit 2
fi
...continuation of shell script

But -prune is always evaluated to true.

What is the more efficient way to write a find expression to achieve this kind of short circuit find?

I would like to use as standard as possible Bourne shell constructs and avoid the use of any temporary file.

dan
  • 933

2 Answers2

3

Note that -prune just stops recursion into subdirectories; it doesn't stop at the first found entry. You probably want -quit with GNU or FreeBSD find or -exit with NetBSD find:

$ find . -name test 
./test
./Y/test

$ find . -name test -print -quit
./test

Instead of testing the return code of find, you can test the output

files=$(find . -name "test" -print -quit)

if [ -n "$files" ]
then
  echo "error... found $files" >&2
  exit 2
fi
-1
find . -name "test" |grep -m1 /test$
Ipor Sircer
  • 14,546
  • 1
  • 27
  • 39