[talk] Concisely determining exit codes of background jobs

Ipsen S Ripsbusker ipsens at ripsbusker.no.eu.org
Thu Feb 14 01:08:44 EST 2019


Matthew Story writes:
> This isn't quite right. Wait with multiple pids will exit with whatever the
> exit code was of the last pid specified so:
>
> ...
>
> Why not just use $!?

Both points are wonderful! wait must be handled differently, and $!
is the correct alternative to jobs -p. I was trying to avoid $! as that
would be more lines than the other suggestions, but it is more correct,
as it avoids some race conditions.

If we include both points, the procedure is like this (untested).

  __pids=
  append_pid() {
    __pids="$__pids $!"
  }

  safe_wait() {
    status=0
    for pid in $__pids; do
      wait $pid || status=1
    done
    return status
  }

  for remote in foo{1,2,3,4,5}; do
    ssh "$remote" bar baz &
    append_pid
  done
  safe_wait




More information about the talk mailing list