jobs
wait
Blocks until specified background jobs or PIDs complete, returning the exit status of the last one waited for. Essential for scripts that launch parallel background work and need to synchronize.
wait [-n] [-f] [ID ...] Common flags / operators
| Flag / Operator | Purpose |
|---|---|
| (no args) | Wait for ALL background children |
| -n | Wait for the next child to finish, return its status (bash 4.3+) |
| -f | Wait for actual termination even if job stopped (bash 5.1+) |
| PID / %job | Wait for a specific PID or job spec |
Examples
cmd1 & cmd2 & wait Fan out two commands in parallel, block until both finish.
cmd & pid=$!; wait "$pid"; echo "status=$?" Capture background PID via $! then get its exit status.
for u in "${urls[@]}"; do curl -s "$u" & done; wait Parallel fetch of a URL list.
wait -n; echo "one finished, status=$?" Return as soon as any one child exits.
Gotcha
Waiting on a PID that already exited returns 127 unless it was a direct child — bash forgets non-child statuses. Under 'set -e', a failing 'wait' exits the script; check status explicitly if you need to tolerate failures.
Related
jobs / bg / fg
Interactive job control: jobs lists background/stopped jobs, bg resumes a stopped job in the background, fg brings it to the foreground. Jobs are addressed with %N, %+, %-, or %string.
trap
Registers a command to run when the shell receives a signal or special event (EXIT, ERR, DEBUG, RETURN). The workhorse for cleanup handlers, temp-file removal, and error diagnostics in scripts.
set (options)
Changes shell option flags and/or replaces positional parameters. The 'safer bash' idiom 'set -euo pipefail' is the most common use — it turns on error-exit, unset-variable-error, and pipeline failure propagation.