I have glossed over the man page for find and -quit
seems to partly do what I want, except it will only cause find
to return non-zero if an error has occurred. So how can find
be forced to return non-zero or at least be spoofed into returning non-zero in a way that is readable to maintainers? So far I have this example:
$ find . -maxdepth 2 -type f \( -exec echo {} \; -o \( -printf "FAIL\n" -a -quit \) \)
./scooby
./shaggy
./velma
./daphne
./fred
$ echo $?
0
But if I replace the echo with a call to false, I get the desired early exit, but no non-zero exit code:
$ find . -maxdepth 2 -type f \( -exec false {} \; -o \( -printf "FAIL\n" -a -quit \) \)
FAIL
$ echo $?
0
Update:
I am trying to get find to return non-zero when -exec
returns false, i.e. the command that executed returned non-zero. Currently, find
just converts the non-zero -exec
call into a boolean state to be used as part of a find
expression.
$ find . -maxdepth 2 -type f \( -exec chmod a+x {} \; -o \( -printf "FAIL\n" -a -quit \) \)
This currently will never return non-zero if the chmod fails. I want to be able to return non-zero if the chmod fails, as well as exit early, which it already does using -quit
.
If you always want to return a non-zero exit code, use && false
as shown below:
find . -maxdepth 2 -type f ... && false
Use grep
to look for the the special FAIL
string printed by find
. It will return zero if the exec
failed, non-zero otherwise.
$ find . -maxdepth 2 -type f \( -exec chmod a+x {} \; -o \( -printf "FAIL\n" -a -quit \) \) | grep -q "FAIL"
find
has the "plus" version of the -exec
command. These actually exit with non-zero status, if one or more invocations of the command fail. So:
find . -maxdepth 2 -type f -exec false "{}" "+"
will give you the desired "fail" exit status. But it will execute your command (here false
) only once, with all files found listed as arguments. So you need to use a command, that can handle a list of files, and that will exit a non-zero status, if processing any of the provided files failed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With