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.
wait [-fn] [-p VAR] [ID...]
Try it
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.
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
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.
127if the PID is not a child of this shell.- Above 128 if
waitwas interrupted by a trapped signal.
Usage notes
- The status of a background job is lost unless you
waitfor it.$?aftercmd &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
waitfor each one separately and OR the statuses. - Limiting parallelism. Start up to N jobs, then
wait -nbefore starting the next. That keeps N running without a job queue. waitreturns early on a trapped signal, so atraphandler can run while you wait.- Pipelines in the background:
waitreturns the status of the last command in the pipeline unlesspipefailis set. - Not a sleep. Use
sleepfor time delays;waitreturns as soon as there is nothing to wait for.
Related
jobs,bgandfg,kill,timeout- Lessons: Jobs and background