Bash wait Command

By 

Updated on

6 min read

Bash wait Command

The wait command waits for one or more background jobs to complete and returns the exit status of the waited-for command. Since it affects the current shell execution environment, wait is implemented as a built-in command in most shells.

In this guide, we will show you how to use the Bash wait command with practical examples.

Syntax

The general syntax of the wait built-in takes the following form:

Terminal
wait [options] ID...

ID is the process or job ID. If no ID is specified, the command waits until all child background jobs are completed.

The wait command returns the exit status of the last command waited for.

For example, to wait for a background process with PID 7654, you would use:

Terminal
wait 7654

When multiple processes are given, the command waits for all processes to complete.

Waiting by Job Specification

Jobs can be specified using the job specification (“jobspec”), which is a way to refer to the processes that make up a job. A jobspec starts with a percentage symbol followed by the job number (%n).

Run a command in the background :

Terminal
rsync -a /home /tmp/home &

The job number (shown in brackets) and process ID will be displayed on your terminal:

output
[2] 54377

You can list active jobs and their IDs with:

Terminal
jobs -l

To wait for the job, run the wait command followed by the job specification:

Terminal
wait %2

Options

The wait command accepts the following options:

Wait for the First Job (-n)

When invoked with the -n option, the command waits only for a single job from the given PIDs or jobspecs to complete and returns its exit status. If no arguments are provided, wait -n waits for any background job to complete:

Terminal
wait -n 45432 54346 76573

Get the Completed Job ID (-p)

By default, wait -n does not show the PID of the job that completed first. Use the -p option to assign it to a variable:

Terminal
wait -p job_id -n 45432 54346 76573

You can then use the captured PID:

Terminal
wait -p job_id -n 45432 54346 76573
echo "First finished PID: $job_id"
Info
The -p option was introduced in Bash 5.1. If you use an older Bash version, you will get an “invalid option” error.

Wait for Actual Termination (-f)

The -f option tells wait to wait for each PID or jobspec to actually terminate before returning its exit code, rather than returning when the job status changes (e.g., when stopped with kill -STOP). This option is only valid when job control is enabled, which is the default for interactive shells.

Examples

The following examples demonstrate common uses of the wait command in Bash scripts.

Waiting for a Single Background Process

wait is typically used in shell scripts that spawn child processes that execute in parallel.

To illustrate how the command works, create the following script:

sh
#!/bin/bash
sleep 30 &
process_id=$!
echo "PID: $process_id"
wait $process_id
echo "Exit status: $?"

Here is what each line does:

  1. The sleep command runs in the background to emulate a time-consuming process.
  2. $! is an internal Bash variable that stores the PID of the last job run in the background. We store it in the process_id variable.
  3. The PID is passed to the wait command, which waits until the sleep command completes.
  4. $? holds the exit status of the last command executed.

If you run the script, it will print something like this:

output
PID: 36353
Exit status: 0

Waiting for the First Job to Complete

Here is an example using the -n option:

sh
#!/bin/bash
sleep 3 &
sleep 30 &
sleep 5 &
wait -n
echo "First job completed."
wait
echo "All jobs completed."

When the script is executed, it spawns 3 background processes. wait -n waits until the first job is completed and the echo statement is printed. wait without arguments waits for all remaining background jobs to complete.

output
First job completed.
All jobs completed.

Understanding the -f Option

This example shows the difference between wait and wait -f. Open the terminal and run:

Terminal
sleep 3600 &
output
[1] 46671

Wait for the process using the PID from the output above:

Terminal
wait 46671

Open another terminal and stop the process with the kill command:

Terminal
kill -STOP 46671

Once the process status changes, the wait command will complete and return the process exit code.

Now repeat the same steps, but this time use wait -f:

Terminal
sleep 3600 &

Use the PID from the output:

Terminal
wait -f 46671

Stop the process from the other terminal:

Terminal
kill -STOP 46671

This time the wait command will not complete. It will continue running until the sleep process actually terminates.

Parallel Execution with Error Handling

A common use case for wait is running multiple tasks in parallel and checking whether any of them failed:

sh
#!/bin/bash
task1() { echo "Running task 1"; sleep 2; }
task2() { echo "Running task 2"; sleep 3; }
task3() { echo "Running task 3"; sleep 1; return 1; }

task1 &
task2 &
task3 &

failed=0
for pid in $(jobs -p); do
  wait "$pid" || ((failed++))
done

if ((failed > 0)); then
  echo "$failed task(s) failed."
  exit 1
fi

echo "All tasks completed successfully."

This script runs three tasks in parallel, waits for each one individually, and counts how many failed.

Quick Reference

TaskCommand
Wait for all background jobswait
Wait for a specific PIDwait 12345
Wait for a job by jobspecwait %1
Wait for the first job to finishwait -n
Get the PID of the completed jobwait -p var -n
Wait for actual terminationwait -f 12345
Get PID of last background jobecho $!

FAQ

What is the difference between wait and wait -n?
wait without arguments waits for all background jobs to complete. wait -n waits for only the first job to finish and returns its exit status.

What does $! do in Bash?
$! is a special Bash variable that holds the process ID (PID) of the last command run in the background.

Can I use wait with commands run in a subshell?
No. wait can only wait for child processes of the current shell. Processes started in a subshell or a different shell session cannot be waited on.

What happens if the PID does not exist?
If the specified PID is not a child of the current shell, wait returns exit status 127.

Conclusion

The wait command waits for background jobs to complete and returns their exit status. It is essential for writing Bash scripts that run tasks in parallel and need to handle their results.

If you have any questions, feel free to leave a comment below.

Tags

Linuxize Weekly Newsletter

A quick weekly roundup of new tutorials, news, and tips.

About the authors

Dejan Panovski

Dejan Panovski

Dejan Panovski is the founder of Linuxize, an RHCSA-certified Linux system administrator and DevOps engineer based in Skopje, Macedonia. Author of 800+ Linux tutorials with 20+ years of experience turning complex Linux tasks into clear, reliable guides.

View author page