How to wait in bash for several subprocesses to finish and return exit code !=0 when any subprocess ends with code !=0? How to wait in bash for several subprocesses to finish and return exit code !=0 when any subprocess ends with code !=0? bash bash

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 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 arrayfor i in $n_procs; do    ./procs[${i}] &    pids[${i}]=$!done# wait for all pidsfor pid in ${pids[*]}; do    wait $piddone


http://jeremy.zawodny.com/blog/archives/010717.html :

#!/bin/bashFAIL=0echo "starting"./sleeper 2 0 &./sleeper 2 1 &./sleeper 3 0 &./sleeper 2 0 &for job in `jobs -p`doecho $job    wait $job || let "FAIL+=1"doneecho $FAILif [ "$FAIL" == "0" ];thenecho "YAY!"elseecho "FAIL! ($FAIL)"fi


Here is simple example using wait.

Run some processes:

$ sleep 10 &$ sleep 10 &$ sleep 20 &$ sleep 20 &

Then wait for them with wait command:

$ wait < <(jobs -p)

Or just wait (without arguments) for all.

This will wait for all jobs in the background are completed.

If the -n option is supplied, waits for the next job to terminate and returns its exit status.

See: help wait and help jobs for syntax.

However the downside is that this will return on only the status of the last ID, so you need to check the status for each subprocess and store it in the variable.

Or make your calculation function to create some file on failure (empty or with fail log), then check of that file if exists, e.g.

$ sleep 20 && true || tee fail &$ sleep 20 && false || tee fail &$ wait < <(jobs -p)$ test -f fail && echo Calculation failed.