← Back to Bash Course | Chapter 11: Process Management | Lesson 3 of 12

The wait Command

wait pauses a script until one or more background jobs it started have actually finished running.

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

bash
#!/bin/bash
(exit 3) &
pid=$!
wait "$pid"
echo "background job exited with status $?"

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

bash
#!/bin/bash
for i in 1 2 3; do
    ( sleep 0.05; echo "job $i done" ) &
done
wait
echo "all jobs finished"

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

bash
#!/bin/bash
(exit 0) &
pid_ok=$!
(exit 1) &
pid_bad=$!

wait "$pid_ok"
echo "first job status: $?"
wait "$pid_bad"
echo "second job status: $?"
Common Mistakes
  1. Calling wait with no arguments and assuming it only waits for the last job; with no arguments it waits for ALL currently running background jobs.
  2. Forgetting that wait $pid returns that job's actual exit status, which is easy to lose track of if not captured immediately.
  3. Trying to wait on 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 since wait only works on the shell's own child jobs.
Chapter Summary
  • wait with no arguments blocks until every background job started by the current shell has finished.
  • wait pid waits for one specific job and returns its exit status as wait's own exit status.
  • wait can only be used on processes that are direct children of the current shell.
  • Capturing $? right after wait pid gives you the backgrounded command's real exit code.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.