In general, if we want to execute a command if find
identifies files corresponding to certain specs, we can use -exec
. But in my case I want to exit the shell/script if find
found a match and -exec
can't do that. [Apparently find
's -exec
cannot call bash functions either.)
For instance in a script to remove a tree if and only if it contains only empty directories, I'd like to first check for presence of any non-directory and abort with an error message at the first such unexpected entry.
So far whenever I need to do something like this, I put the output to a variable (possibly using -quit
with find
) and testing for it being empty or not.
So my script looks like:
#! /bin/sh
INTRUDER="$(find "$@" ! -type d -print -quit)"
if [ -n "$INTRUDER" ] ; then
echo "Found non-dir $INTRUDER; leaving the arguments untouched"
exit 1
fi
rm -R "$@"
Is there a different/better approach than this? By "better" I mean, smaller to code, more portable (if there is any portability issue with the above), etc. By "different" I mean by avoiding the extra variable and testing for its length.
-quit
. But it merely stops searching after first match. I am asking for a workaround to not being able to-exec
a shell built-in (for this particular example to exit the shell, not exit thefind
). So this is not a dup. Please remove that tag.