Home > Process Management > wait

wait: Wait for Background Job Completion

The `wait` command is used to pause execution until a specified background job or process (PID) terminates. It is particularly useful in scripts where multiple tasks are run concurrently, and the script needs to wait for all of them to complete before proceeding.

Overview

True to its name, `wait` pauses the execution of a shell script until a background job finishes. It is typically used when multiple tasks are run in parallel in the background (using the `&` symbol), and subsequent operations in the script depend on these background tasks completing. Using `wait` also allows the script to check the exit code of the background process, which helps in determining the success or failure of the job.

Key Features

Key features of the `wait` command include:

  • Waits for the termination of a specific background job.
  • Can take a job number or Process ID (PID) as an argument.
  • If executed without arguments, it waits for all background jobs to terminate.
  • Useful for synchronizing multiple parallel tasks in shell scripts.

Main Options

The `wait` command is a simple command with few options, primarily taking job numbers or PIDs as arguments.

1) Execution Options

2) Help

Generated command:

Try combining the commands.

Description:

`wait` Executes the command.

Combine the above options to virtually execute commands with AI.

Usage Examples

Explore various usage examples of the `wait` command to understand its functionality.

Wait for All Background Jobs

sleep 5 &
sleep 10 &
jobs
wait
echo 'All jobs have completed.'

Run multiple `sleep` tasks in the background, then use the `wait` command to wait for all of them to complete.

Wait for a Specific Job

sleep 10 &
sleep 5 &
jobs
wait %1
echo 'Job 1 has completed.'

Wait for job number 1 to finish among two jobs. Use the `jobs` command to find the job number and then `wait %1`.

Wait by Process ID (PID)

sleep 10 &
PID=$!
echo "Job with PID $PID has started."
wait $PID
echo "Job with PID $PID has completed."

In a script, save the PID of a background process into a variable using `$!`, then wait for that specific PID to terminate.

Installation

wait is a built-in command of shells (like bash, zsh), and does not require separate installation.

Tips & Cautions

Here are some points to keep in mind when using the `wait` command.

Tips

  • `wait` pauses shell execution until the background process terminates. If the process does not terminate, the shell will continue to wait indefinitely.
  • The exit status code of the `wait` command is the same as the exit status code of the process it waited for. This allows you to check the success or failure of the job within your script.
  • To use a job number (`%1`), you must first check the current shell's background jobs using the `jobs` command. `$!` is a special variable that holds the PID of the most recently executed background process.

Same category commands