Background jobs and wait
Appending & starts an asynchronous command: the parent can continue before the child finishes. Save $! immediately to identify the most recently started background job. The launch status does not tell you whether the child succeeded. Use wait "$pid" in the same shell to collect the child’s status; place it in an if condition to handle failure even with errexit enabled. Waiting for several IDs in one call returns the last ID’s status, not an aggregate. With no arguments, wait normally returns zero after waiting for running background jobs. Bash 5.2 supports wait -n for one completion and wait -p var with -n to identify it; check help wait on other versions. Use only a small number of known children, fixed work and a deadline. An interrupted wait is not proof that the child ended; a saved PID is not permanent ownership evidence. Without job control, wait normally waits for termination; with job control enabled, wait -f requests termination rather than a mere status change. A successful wait with no IDs is not evidence that every child succeeded.
Practical examples
Run each example as a separate script in a fresh noninteractive Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Collect one child status
( exit 7 ) &pid=$!if wait "$pid"; then printf 'success\n'else printf 'child=%s\n' "$?"fiExpected stdout:
child=7The wait reports the child’s status, not the launch status.
Collect two statuses
( exit 4 ) &a=$!( exit 0 ) &b=$!wait "$a"; ra=$?wait "$b"; rb=$?printf 'a=%s b=%s\n' "$ra" "$rb"Expected stdout:
a=4 b=0Separate waits preserve both results.
Identify a completion
( sleep 0.3; exit 6 ) &pid=$!wait -n -p finished "$pid"rc=$?[[ ${finished-} == "$pid" ]] || exit 1printf 'matched status=%s\n' "$rc"Expected stdout:
matched status=6The short delay gives the shell time to enter wait. The identifier is checked, not printed. This is a fixed local demonstration, not a general scheduling guarantee.
Common mistakes
Do not interpret the status of & as the child result. Do not lose $! by launching a second job before saving it. Do not use bare wait as a failure aggregator.
Practice
Launch two fixed children returning 0 and 5. Save both PIDs, collect both statuses separately, and print an aggregate failure flag. No sleeps longer than one second or unrelated processes.
Next: Interactive job control