Waiting for Processes with wait
wait is the Bash built-in that pauses the shell until background jobs have finished, and it is the only way for a script to learn the exit status of a command it started with &. Starting a job with & gives no information about how the job ends ($? is always 0 at that moment, lesson 136); wait closes that gap.
A script that starts background work uses wait for three purposes:
- Synchronization: do not continue until certain jobs are done, for example before reading the files they produce.
- Error checking: find out which jobs succeeded and which failed.
- Flow control: react as soon as any job finishes, which is how a script keeps a fixed number of jobs running.
All examples were run with Bash 5.2 as scripts, each in a fresh shell, so that leftover jobs from one test could not affect another.
Syntax
wait [-fn] [-p varname] [id ...]
| Form | Waits for | Returns |
|---|---|---|
wait | all background jobs of this shell | 0 |
wait PID | the process with that ID | its exit status |
wait %N | job number N | its exit status |
wait PID1 PID2 ... | each listed process, in turn | the status of the last one listed |
wait -n | any one job (Bash 4.3+) | that job's status |
wait -n -p VAR | any one job, storing its PID in VAR (Bash 5.1+) | that job's status |
The -f option matters only when job control is on (lesson 137): it makes wait wait until the job has really ended, not merely changed state, for example by being stopped.
wait can only wait for children of the current shell, meaning processes this shell itself started. It cannot wait for a process started by another terminal or another script.
Waiting for All Jobs
Without arguments, wait blocks until every background job has ended:
(sleep 0.2; exit 3) & (sleep 0.1; exit 5) &
wait
echo "wait status: $?"
wait status: 0
Both jobs failed, yet wait returned 0. The plain form only answers "is everything finished?", never "did everything succeed?". It is the right tool before a step that needs all results, but on its own it hides failures.
Waiting for a Specific Process
To get a job's exit status, save its PID from $! (lesson 139) right after starting it, and pass it to wait:
(sleep 0.2; exit 3) & p1=$!
(sleep 0.1; exit 5) & p2=$!
wait "$p1"; echo "job 1: $?"
wait "$p2"; echo "job 2: $?"
job 1: 3
job 2: 5
Job 2 finished first, but its status was not lost: Bash records the status of each background child when it ends, and wait "$p2" returned it later. This holds even when the job ended long before wait was called:
(exit 7) & p=$!
sleep 0.3
wait "$p"; echo "finished long ago: $?"
wait "$p"; echo "second wait same pid: $?"
finished long ago: 7
second wait same pid: 7
So the usual pattern is safe: start all jobs, collect their PIDs, then wait for each PID in any order.
With several IDs in one call, wait waits for all of them but returns only the status of the last ID in the list:
(exit 3) & a=$!; (exit 5) & b=$!
wait "$a" "$b"; echo "wait a b: $?"
wait "$b" "$a"; echo "again b a: $?"
wait a b: 5
again b a: 3
To check every job, call wait once per PID in a loop:
pids=()
for f in "$@"; do
gzip -k -- "$f" &
pids+=("$!")
done
failed=0
for pid in "${pids[@]}"; do
wait "$pid" || failed=$(( failed + 1 ))
done
echo "$failed job(s) failed"
Run as bash gz.sh x1.txt nope.txt x2.txt, it created x1.txt.gz and x2.txt.gz and reported the missing file:
gzip: nope.txt: No such file or directory
1 job(s) failed
Jobs Ended by Signals
When a job is ended by a signal, wait returns 128 plus the signal number, the same convention as $? (lesson 116):
sleep 5 & p=$!
kill "$p"
wait "$p"; echo "killed: $? ($(kill -l $?))"
killed: 143 (TERM)
kill -l 143 translates the status back into a signal name: 143 − 128 = 15, SIGTERM.
Waiting with a Job Specification
wait %N works with job numbers, as fg and kill do (lesson 137):
sleep 0.1 & wait %1; echo "wait %1: $?"
wait %1; echo "wait %1 again: $?"
wait %1: 0
n3.sh: line 2: wait: %1: no such job
wait %1 again: 127
Once a job has been waited for, it leaves the job table, so the jobspec no longer exists. In scripts, PIDs are more dependable than job numbers, because a script rarely knows which number Bash assigned.
Errors: Status 127
wait returns 127 when the ID is not a child of this shell:
wait 1; echo "wait 1: $?"
wait 999999; echo "wait 999999: $?"
a.sh: line 19: wait: pid 1 is not a child of this shell
wait 1: 127
a.sh: line 20: wait: pid 999999 is not a child of this shell
wait 999999: 127
To wait for a process that is not your child, for example a server started by another script, poll it with kill -0 PID in a loop (lesson 140).
Waiting for the Next Job with wait -n
wait -n returns as soon as any one job ends, with that job's exit status. It was added in Bash 4.3.
(sleep 0.3; exit 1) & (sleep 0.1; exit 2) & (sleep 0.2; exit 3) &
wait -n; echo "first: $?"
wait -n; echo "second: $?"
wait -n; echo "third: $?"
wait -n; echo "nothing left: $?"
first: 2
second: 3
third: 1
nothing left: 127
The jobs were reported in the order they finished (0.1, 0.2 and 0.3 seconds). When no unwaited job is left, wait -n returns 127.
A job that has already ended but has not been waited for counts as well, so wait -n returns immediately in that case:
(exit 3) &
sleep 0.2
wait -n; echo "wait -n after the job already ended: $?"
wait -n after the job already ended: 3
wait -n also accepts a list of IDs and then waits only for the first of those:
(sleep 0.3; exit 1) & s=$!
(sleep 0.1; exit 2) & f=$!
(sleep 0.05; exit 9) & o=$!
wait -n "$s" "$f"; echo "first of s and f: $?"
wait "$o"; echo "o: $?"
first of s and f: 2
o: 9
Job o ended first, but it was not in the list, so wait -n ignored it and returned when job f ended.
Knowing Which Job Finished: -p
The status alone does not tell you which job finished. Since Bash 5.1, -p VAR stores the PID of the job that ended in a variable:
(sleep 0.2; exit 4) & x=$!
(sleep 0.1; exit 6) & y=$!
echo "x=$x y=$y"
wait -n -p done_pid; echo "pid $done_pid status $?"
wait -n -p done_pid; echo "pid $done_pid status $?"
wait -n -p done_pid; echo "nothing left: status $? var='${done_pid-unset}'"
x=691 y=692
pid 692 status 6
pid 691 status 4
nothing left: status 127 var='unset'
When nothing was left to wait for, Bash unset the variable, so ${done_pid-unset} printed the fallback text. Checking whether the variable is set is therefore a reliable way to detect that the pool of jobs is empty.
wait and Signals
When the script has a trap for a signal and that signal arrives while wait is blocking, wait returns at once with status 128 + the signal number, the trap runs, and the job keeps running:
trap 'echo "got USR1"' USR1
sleep 2 & p=$!
( sleep 0.3; kill -USR1 $$ ) &
wait "$p"; echo "wait returned $? ($(kill -l $?))"
kill -0 "$p" && echo "sleep still running"
wait "$p"; echo "second wait: $?"
got USR1
wait returned 138 (USR1)
sleep still running
second wait: 0
A foreground command delays a trap until it ends (lesson 123 measured a three-second delay with a foreground sleep 3). Running the long command in the background and waiting for it lets the trap react immediately. A status above 128 from wait can therefore mean either "the job was killed" or "wait itself was interrupted"; a script that uses traps can check with kill -0 whether the job is still alive and call wait again.
Portability
wait with no arguments and wait PID are POSIX and work in every shell. wait -n and -p are Bash extensions. Dash rejected -n:
d.sh: 3: wait: Illegal option -n
A Complete Example: A Job Pool
runpool.sh reads one shell command per line from a task file and runs them in the background, keeping at most N running at the same time (-j N, default 2). As soon as one task ends, it reports the result and starts the next one. This is the improvement over the batch approach from lesson 136, where a single slow job held up the whole batch.
#!/usr/bin/env bash
# runpool.sh [-j N] TASKFILE: run each line of TASKFILE as a command,
# at most N at a time, and report every task's exit status.
set -uo pipefail
(( BASH_VERSINFO[0] > 5 || (BASH_VERSINFO[0] == 5 && BASH_VERSINFO[1] >= 1) )) ||
{ echo "${0##*/}: needs Bash 5.1 or later (wait -p)" >&2; exit 2; }
max=2
if [[ ${1-} == -j ]]; then max=${2-}; shift; shift; fi
[[ $max =~ ^[1-9][0-9]*$ ]] || { echo "${0##*/}: invalid -j value: $max" >&2; exit 2; }
(( $# == 1 )) || { echo "usage: ${0##*/} [-j N] TASKFILE" >&2; exit 2; }
taskfile=$1
[[ -f $taskfile && -r $taskfile ]] || { echo "${0##*/}: cannot read $taskfile" >&2; exit 2; }
declare -A task_of=() start_of=() # PID -> task line, PID -> start time
failed=0 total=0
now_ms() { local t=${EPOCHREALTIME/./}; echo $(( t / 1000 )); }
reap_one() { # wait for any one job and report it
local pid status
wait -n -p pid
status=$?
[[ -n ${pid-} ]] || return 1 # no job was left to wait for
local ms=$(( $(now_ms) - start_of[$pid] ))
if (( status == 0 )); then
printf 'ok %5d ms %s\n' "$ms" "${task_of[$pid]}"
else
printf 'FAIL %5d ms %s (status %d)\n' "$ms" "${task_of[$pid]}" "$status"
failed=$(( failed + 1 ))
fi
unset 'task_of[$pid]' 'start_of[$pid]'
}
while IFS= read -r task || [[ -n $task ]]; do
[[ -z ${task//[[:space:]]/} || $task == \#* ]] && continue
while (( ${#task_of[@]} >= max )); do reap_one; done # pool is full
bash -c "$task" < /dev/null &
task_of[$!]=$task
start_of[$!]=$(now_ms)
total=$(( total + 1 ))
done < "$taskfile"
while (( ${#task_of[@]} > 0 )); do reap_one; done # drain the pool
echo "$total task(s), $failed failed"
(( failed == 0 ))
How It Works
- Two associative arrays (lesson 102) map each running job's PID to its task line and its start time. The number of elements,
${#task_of[@]}, is the number of running jobs. They are declared with=()so thatset -utreats them as set even while empty; without it,${#task_of[@]}on the empty array stopped the first test run withtask_of: unbound variable. reap_onecallswait -n -p pid, which blocks until any job ends, and receives its PID and exit status. It prints the result, counts failures, and removes the job from both arrays, which frees a slot in the pool. Ifpidstays unset, there was nothing to wait for, and the function returns 1.- The read loop (lesson 114) skips blank lines and comments. Before starting a task, an inner
whilecallsreap_oneuntil the pool has a free slot. The task then starts withbash -c "$task" &, and its PID from$!becomes the key in both arrays. < /dev/nullkeeps the tasks from reading the task file. Without it, a task that reads standard input would consume the next lines of the loop's input (lesson 114 showed this problem withhead).- The drain loop after the read loop waits for the jobs that are still running. The final
(( failed == 0 ))makes the exit status 0 only if every task succeeded. - Trust: each line is executed as a shell command, so the task file must come from a trusted source, exactly like a script.
Running the Complete Example
tasks.txt contains five tasks with different durations; two of them fail:
# one command per line
sleep 1.0
sleep 0.4; exit 3
sleep 0.6
sleep 0.2
ls /no/such/dir
With the default of two jobs at a time (the total time was measured with time):
$ bash runpool.sh tasks.txt
FAIL 404 ms sleep 0.4; exit 3 (status 3)
ok 1006 ms sleep 1.0
ok 606 ms sleep 0.6
ls: cannot access '/no/such/dir': No such file or directory
FAIL 4 ms ls /no/such/dir (status 2)
ok 204 ms sleep 0.2
5 task(s), 2 failed
total 1.2s
The timeline explains the order. sleep 1.0 and the failing sleep 0.4 started together. At 0.4 seconds, wait -n reported the failure, and sleep 0.6 took the free slot. At about 1.0 second, both running tasks ended, so sleep 0.2 and ls started; ls failed almost immediately, and sleep 0.2 ended at about 1.2 seconds. The exit status was 1.
With five slots, everything ran at once, and the results appeared in order of duration:
$ bash runpool.sh -j 5 tasks.txt
ls: cannot access '/no/such/dir': No such file or directory
FAIL 4 ms ls /no/such/dir (status 2)
ok 203 ms sleep 0.2
FAIL 403 ms sleep 0.4; exit 3 (status 3)
ok 604 ms sleep 0.6
ok 1006 ms sleep 1.0
5 task(s), 2 failed
total 1.0s
With -j 1, the tasks ran one after another, in file order, and took 2.2 seconds. Invalid input is rejected with status 2:
$ bash runpool.sh -j x tasks.txt
runpool.sh: invalid -j value: x
$ bash runpool.sh
usage: runpool.sh [-j N] TASKFILE
$ bash runpool.sh missing.txt
runpool.sh: cannot read missing.txt
A last line without a newline is still read (|| [[ -n $task ]]), and a task file of only echo hi and sleep 0.1 printed hi, two ok lines and 2 task(s), 0 failed with status 0. The millisecond values will differ slightly on your machine.