I’m writing a quick script to list all the files in a directory, run a function on each of them, and then print out the status code. Now the status code I would like is of the entire transaction and not the last expression 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 directory. When file1.txt
gets passed to -exec
its status code is 1
but calls to file2.txt
and file3.txt
return 0
. When I call echo $?
at the end it returns 0
from the last expression executed despite the call on file1.txt
returning a 1
. What I would like is a status code that’s nonzero if any of the expressions return a nonzero value in the above script just like what was described for file1.txt
. How would I go about that?
Advertisement
Answer
I will 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 exist status is 1
from my_function
.