0

I'm trying to run multiple background processes and then exit with an error if any of them fail. For whatever reason, I cannot get the exit status from wait to behave as documented. This is maddening because if I try wait manually from the command line, I get the expected results, but when I try to run my script which launches remote processes, wait always succeeds.

#!/bin/bash -ex
# ...
pids=
for remote in $REMOTE; do
    ssh $remote run-script.sh & pids=${pids:+${pids} }$!
done

set +e
wait $pids
result=$?
set -e

echo $result    # should be nonzero because remote script exits with 1

debug output (the exit 1 is from the remote script)

++ pids=
++ for remote in '$REMOTE'
++ pids=8142
++ set +e
++ wait 8142
++ ssh user@host run-script.sh
++ exit 1
++ result=0
++ set -e
++ echo 0
0

I've also tried using jobs but abandoned it because of inconsistent results if the script ends quickly:

wait < <(jobs -p)
rich remer
  • 3,407
  • 2
  • 34
  • 47
  • 1
    `wait` returns the status of the last job that exited. It doesn't always succeed, only if the last job succeeds. – Gilles 'SO- stop being evil' May 09 '16 at 20:19
  • Duplicate question. There are several answers on here, but Charles Duffy gives good information here. http://stackoverflow.com/questions/36316040/exit-a-bash-script-if-an-error-occurs-in-it-or-any-of-the-background-jobs-it-cre summary of the issue: by default wait will only return the status of the last command. – SaintHax May 09 '16 at 20:14

0 Answers0