wait - Linux


Overview

The wait command in Linux is used to pause the execution of a shell script until all background jobs or a specific job ID has finished executing. It is primary used in shell scripting to manage the order in which scripts and commands run, ensuring that a script waits for resource-intensive or critical jobs to complete before continuing.

Syntax

The basic syntax of the wait command is:

wait [options] [job_specification]
  • job_specification: This can include job IDs or process IDs (PIDs) that the shell should wait on. If no job ID is specified, the command waits for all currently active child processes.

Options/Flags

The wait command does not usually have many options. Here are the most commonly used scenarios:

  • [job_id]: When specified, wait pauses the script execution until the background job with the specified job_id completes. If no job ID is specified, it waits for all background jobs to complete.

Examples

  1. Wait for a specific job to complete:

    If you start a process in the background like so:

    sleep 30 &
    

    You can use the wait command with the job ID to wait for the completion of this particular job:

    wait %1
    echo "Job 1 has completed."
    
  2. Wait for all background jobs to complete:

    If you have multiple background jobs running:

    sleep 30 &
    sleep 45 &
    

    Simply use wait without a job ID:

    wait
    echo "All background jobs have completed."
    

Common Issues

  • Unexpected job completion: Sometimes, jobs complete in an unexpected order, which can lead to issues if the script expects them to finish in the order they started. Plan the order of commands and use wait judiciously to control execution flow.

  • Not finding the job ID: If a job completes before wait is called with its job ID, wait will return immediately since there is no job to wait for. Ensure the correct job IDs are used.

Integration

The wait command is powerful when used in conjunction with complex shell scripts where multiple background processes are launched. For example:

# Begin three background processes
do_task_1 & pid1=$!
do_task_2 & pid2=$!
do_task_3 & pid3=$!

# Wait for all tasks to complete
wait $pid1
echo "Task 1 completed"
wait $pid2 $pid3
echo "Tasks 2 and 3 completed"

This script shows how you can store the process IDs of background jobs and use wait to synchronize their completion.

  • jobs: Lists active jobs along with their statuses and job IDs.
  • bg: Resumes suspended jobs by running them in the background.
  • fg: Brings background or suspended jobs to the foreground.

For more about scripting and job control in bash, consult the Bash Reference Manual or the online documentation specific to your shell environment.