Interview Prep/Shell Scripting/Shells, scripts and execution

How do you run a command in the background, wait for it and collect its exit code?

IntermediateConceptShells, scripts and execution
Answer
pids=()
for host in web1 web2 web3; do
  ssh -o BatchMode=yes "$host" 'sudo systemctl restart app' &
  pids+=("$!")
done
rc=0
for pid in "${pids[@]}"; do
  wait "$pid" || rc=1          # wait PID returns that job's exit status
done
exit "$rc"

Plain wait with no arguments waits for all jobs but always returns 0, so failures are lost. Bash 5.1+ also has wait -n -p var to handle whichever job finishes first.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Shells, scripts and execution