I\'m trying to run 3 commands in parallel in bash shell:
$ (first command) & (second command) & (third command) & wait
The prob
The shell function below will wait for all PIDs passed as arguments to finish, returning 0 if all PIDs executed without error.
The first PID that exists with an error will cause the PIDs that come after it to be killed, and the exit code that caused the error will be returned by the function.
wait_and_fail_on_first() {
local piderr=0 i
while test $# -gt 0; do {
dpid="$1"; shift
wait $dpid || { piderr=$?; kill $@; return $piderr ;}
} done
}
Here's how to use it:
(first command) & pid1=$!
(second command) & pid2=$!
(third command) & pid3=$!
wait_and_fail_on_first $pid1 $pid2 $pid3 || {
echo "PID $dpid failed with code $?"
echo "Other PIDs were killed"
}