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.
More on Shells, scripts and execution
What is a shell, and how is Bash different from sh, dash and zsh?BeginnerWhat does the shebang line do, and why prefer `#!/usr/bin/env bash` over `#!/bin/bash`?BeginnerWhat is the difference between `./script.sh`, `bash script.sh` and `source script.sh`?BeginnerWhat happens when you type a command name? How does Bash decide what to run?AdvancedWhy must `cd`, `export` and `read` be builtins rather than external programs?IntermediateWhat is the difference between a login, interactive and non-interactive shell, and which startup files run?Intermediate