Status after each argument passed to -exec in search

I am writing a quick script to list all files in a directory, run a function on each one, and then print the status code. Now the status code I need is for the entire transaction, not the last statement that was executed. For example...

find ./ -maxdepth 1 -name \*.txt -exec my_function {} \;

      

Let's say I have the following files file1.txt

, file2.txt

, file3.txt

in my catalog. When file1.txt

it passed to -exec

his status code 1

, but causes file2.txt

and file3.txt

return statement 0

. When I call echo $?

at the end, it returns 0

from the last expression executed despite the call file1.txt

returning 1

. I would like the status code to be non-null if any of the expressions return non-null in the above script in the same way as described in file1.txt

. How can i do this?

+3


source to share


4 answers


I suggest something like this:

status=0
while IFS= read -d '' -r file; do
   my_function "$file"
   ((status |= $?))
done < <(find . -maxdepth 1 -name '*.txt' -print0)

echo "status=$status"

      



This will print status=1

if any of the existing states are 1

out of my_function

.

+1


source


find . -maxdepth 1 -name \*.txt  -print0 | xargs -r0 -I {} sh -c "echo {}; echo $?;"

      

Following the suggestions received from lcd047

, to avoid problems with containing names "

, the best solution is



find . -maxdepth 1 -name \*.txt  -print0 | xargs -r0 -I {} sh -c 'printf "%s\n" "$1"; echo $?' sh {} \;

      

0


source


You can do something like this (tested with GNU find) that will print a line for each file for which exec returns a non-zero status:

find . -maxdepth 1 -name "*.txt" '(' -exec my_function {} \; -o -printf 1\\n ')'

      

You can use a -printf

more descriptive file name, for example, to print. But in any case, there will be an exit if it my_function

does not work for some file. (Or if it prints something.)

0


source


Although it -exec ... \;

returns the exit status as a true primary, -exec ... {} +

causes the call to find

return a non-zero exit status if any call returns a non-zero exit status (and always returns true as primary, since one call can process multiple files).

If it my_function

takes multiple arguments, then

find ./ -maxdepth 1 -name \*.txt -exec my_function {} \;

      

will do the job.

If not, you can do

find ./ -maxdepth 1 -name \*.txt -exec sh -c 'r=0; for arg do my_function "$arg" || r=1; done; exit "$r"' sh {} \;

      

0


source







All Articles