I want to run the command
find some/path -exec program \{} \;
but I want the find command to quit as soon as the command
program \{}
fails on any of the files found.
Is there a simple way of doing this?
Exit When Any Command Fails This can actually be done with a single line using the set builtin command with the -e option. Putting this at the top of a bash script will cause the script to exit if any commands return a non-zero exit code.
Extracting the elusive exit code To display the exit code for the last command you ran on the command line, use the following command: $ echo $? The displayed response contains no pomp or circumstance. It's simply a number.
I think it is not possible to achieve what you want, only with find -exec
.
The closest alternative would be to do pipe find
to xargs
, like this:
find some/path -print0 | xargs -0 program
or
find some/path -print0 | xargs -0L1 program
This will quit if program terminates with a non-zero exit status
print0
is used so that files with newlines in their names can be handled -0
is necessary when -print0
is used L1
tells xargs
program to execute program with one argument at a time (default is to add all arguments in a single execution of program)If you only have sane file names, you can simplify like this:
find some/path | xargs program
or
find some/path | xargs -L1 program
Finally, If program takes more than one argument, you can use -i
combined with {}
. E.g.
find some/path | xargs -i program param1 param2 {} param4
In addition to the other fine answers, GNU find (at least) has a -quit
predicate:
find path -other -predicates \( -exec cmd {} \; -o -quit \)
The -quit
predicate is certainly non-standard and does not exist in BSD find.
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