How to wait in bash for several subprocesses to finish, and return exit code !=0 when any subprocess ends with code !=0?
wait
also (optionally) takes the PID
of the process to wait for, and with $!
you get the PID
of the last command launched in the background.
Modify the loop to store the PID
of each spawned sub-process into an array, and then loop again waiting on each PID
.
# run processes and store pids in array
for i in $n_procs; do
./procs[${i}] &
pids[${i}]=$!
done
# wait for all pids
for pid in ${pids[*]}; do
wait $pid
done
http://jeremy.zawodny.com/blog/archives/010717.html :
#!/bin/bash
FAIL=0
echo "starting"
./sleeper 2 0 &
./sleeper 2 1 &
./sleeper 3 0 &
./sleeper 2 0 &
for job in `jobs -p`
do
echo $job
wait $job || let "FAIL+=1"
done
echo $FAIL
if [ "$FAIL" == "0" ];
then
echo "YAY!"
else
echo "FAIL! ($FAIL)"
fi