Waiting for Processes with wait

Su Suriya Ravichandran Updated 06 Dec 2026
12 min read ·Lesson 138 of 205

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:

  1. Synchronization: do not continue until certain jobs are done, for example before reading the files they produce.
  2. Error checking: find out which jobs succeeded and which failed.
  3. 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 ...]
FormWaits forReturns
waitall background jobs of this shell0
wait PIDthe process with that IDits exit status
wait %Njob number Nits exit status
wait PID1 PID2 ...each listed process, in turnthe status of the last one listed
wait -nany one job (Bash 4.3+)that job's status
wait -n -p VARany 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 that set -u treats them as set even while empty; without it, ${#task_of[@]} on the empty array stopped the first test run with task_of: unbound variable.
  • reap_one calls wait -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. If pid stays 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 while calls reap_one until the pool has a free slot. The task then starts with bash -c "$task" &, and its PID from $! becomes the key in both arrays.
  • < /dev/null keeps 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 with head).
  • 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.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Waiting for Processes with wait and get answers drawn from it.

Signed-in readers only.