Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exit from find -exec if it fails on one of the files

Tags:

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?

like image 863
FORTRAN Avatar asked Feb 14 '13 09:02

FORTRAN


People also ask

How do you exit a script if command fails?

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.

How do I get exit status from last command?

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.


2 Answers

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

  • the print0 is used so that files with newlines in their names can be handled
  • -0 is necessary when -print0 is used
  • the 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
like image 145
user000001 Avatar answered Sep 30 '22 18:09

user000001


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.

like image 24
kojiro Avatar answered Sep 30 '22 18:09

kojiro