Skip to content
Tutorials Center
My learning

Topics

Linux Command Reference ยท Processes and Signals

Bash wait command

Reference for the Bash wait builtin: wait for all or specific background jobs, collect their exit status, use wait -n and -p, and run tasks in parallel safely.

wait pauses the shell until background jobs finish. With no arguments it waits for all of them. With a process ID or job spec it waits for that one and returns its exit status, which is the only reliable way to learn whether a background command succeeded.

It is a shell builtin, so it only knows the children of the current shell. You cannot wait for a process started by someone else, or for a grandchild.

Terminal
wait [-fn] [-p VAR] [ID...]

Try it

Bash Collect exit statuses from parallel jobs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Bash wait -n: handle jobs as they finish

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Syntax

Terminal
wait                    # all background jobs
wait ID...              # specific PIDs or job specs (%1)
wait -n [ID...]         # next job to finish
wait -n -p VAR [ID...]  # also store its PID in VAR
Option Description
-n Wait for any one job to finish and return its status (Bash 4.3+).
-p VAR With -n, store the PID of the job that finished in VAR (Bash 5.1+, not in 5.0).
-f Wait until the job has terminated, not just changed state (Bash 5.0+).

Returns:

  • With no arguments: 0 after all children ended.
  • With IDs: the exit status of the last ID waited for.
  • 127 if the PID is not a child of this shell.
  • Above 128 if wait was interrupted by a trapped signal.

Usage notes

  • The status of a background job is lost unless you wait for it. $? after cmd & only says the job was started.
  • $! holds the PID of the most recent background command. Save it right away if you start several: pid=$!.
  • Failure in a loop. To run a list of commands in parallel and fail if any fails, record each PID, then wait for each one separately and OR the statuses.
  • Limiting parallelism. Start up to N jobs, then wait -n before starting the next. That keeps N running without a job queue.
  • wait returns early on a trapped signal, so a trap handler can run while you wait.
  • Pipelines in the background: wait returns the status of the last command in the pipeline unless pipefail is set.
  • Not a sleep. Use sleep for time delays; wait returns as soon as there is nothing to wait for.