The wait Command
In this page:
Waiting for a Specific Job
wait pid blocks the script until that particular background process finishes, and then wait itself returns that process's exit status, which becomes available in $?.
Example: Waiting for a Specific Job
#!/bin/bash
(exit 3) &
pid=$!
wait "$pid"
echo "background job exited with status $?"
Login to try C/C++/Java/PHP code in the editor
Waiting for All Background Jobs
Calling wait with no arguments blocks until every background job the current shell started has completed, regardless of how many there are.
Example: Waiting for All Background Jobs
#!/bin/bash
for i in 1 2 3; do
( sleep 0.05; echo "job $i done" ) &
done
wait
echo "all jobs finished"
Login to try C/C++/Java/PHP code in the editor
Collecting Multiple Exit Statuses
To check the individual result of several background jobs, save each PID and wait on them one at a time, since a bare wait with no arguments only tells you that everything finished, not each job's individual outcome.
Example: Collecting Multiple Exit Statuses
#!/bin/bash
(exit 0) &
pid_ok=$!
(exit 1) &
pid_bad=$!
wait "$pid_ok"
echo "first job status: $?"
wait "$pid_bad"
echo "second job status: $?"
Login to try C/C++/Java/PHP code in the editor
- Calling
waitwith no arguments and assuming it only waits for the last job; with no arguments it waits for ALL currently running background jobs. - Forgetting that
wait $pidreturns that job's actual exit status, which is easy to lose track of if not captured immediately. - Trying to
waiton a PID that was not started as a direct child of the current shell (e.g. a PID from a completely separate process), which fails sincewaitonly works on the shell's own child jobs.
waitwith no arguments blocks until every background job started by the current shell has finished.wait pidwaits for one specific job and returns its exit status aswait's own exit status.waitcan only be used on processes that are direct children of the current shell.- Capturing
$?right afterwait pidgives you the backgrounded command's real exit code.
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: