wait

shell builtinLinux/Unix
The wait command is one of the most frequently used commands in Linux/Unix-like operating systems. wait Wait for process completion and return exit status

Quick Reference

Command Name:

wait

Category:

shell builtin

Platform:

Linux/Unix

Basic Usage:

wait [options] [arguments]

Common Use Cases

    Syntax

    wait [options] [id...]

    Options

    Option Description
    -n Wait for the next job to terminate and return its exit status (Bash 4.3+)
    -f Wait until the specified process ID or job ID terminates, instead of waiting only if it is a child process (Bash 5.1+)
    -p pid Wait for the process with the specified process ID to terminate (Bash 5.1+)
    id Process ID, job ID, or job specification to wait for. If not specified, waits for all child processes.

    Special IDs

    ID Format Description
    number Process ID (PID)
    %number Job number
    %string Job whose name begins with string
    %?string Job whose command contains string
    $! Process ID of the most recently executed background command

    Examples

    How to Use These Examples

    The examples below show common ways to use the wait command. Try them in your terminal to see the results. You can copy any example by clicking on the code block.

    # Basic Examples Basic
    # Wait for all background jobs to finish wait
    # Wait for a specific process ID wait 1234
    # Wait for a specific job wait %1
    # Advanced Examples Advanced
    # Wait for multiple processes wait 1234 5678 9012
    # Wait for specific jobs wait %1 %2 # Run a command in the background and wait for it to complete sleep 10 & wait $! # Start multiple commands and wait for all of them sleep 5 & echo "First process PID: $!" sleep 10 & echo "Second process PID: $!" wait # Wait for a process with a specific return code ./my_script.sh & wait $! echo "Script exited with status $?" # Use wait with timeout (bash 4.4+) sleep 30 & wait -n # Wait for any job to complete echo "A job has completed"

    Try It Yourself

    Practice makes perfect! The best way to learn is by trying these examples on your own system with real files.

    Understanding Syntax

    Pay attention to the syntax coloring: commands, options, and file paths are highlighted differently.

    Notes

    The `wait` command is a shell builtin that pauses script execution until one or more background processes complete. It's a fundamental tool for shell scripting, particularly for managing parallel execution and synchronization of multiple processes. **Core Functionality:** 1. **Process Synchronization**: wait allows a shell script to start background processes and then wait for them to complete before proceeding with subsequent commands. 2. **Exit Status Retrieval**: When waiting for a specific process, wait returns the exit status of that process, enabling scripts to determine if the process completed successfully. 3. **Job Control Integration**: wait works seamlessly with the shell's job control system, allowing scripts to wait for jobs specified by job ID rather than just process ID. **Common Use Cases:** 1. **Parallel Processing**: Scripts can start multiple processes in the background and then use wait to ensure all processing is complete before proceeding. 2. **Parent-Child Synchronization**: A parent script can start a child process and wait for it to complete before continuing execution. 3. **Error Handling**: By capturing the exit status of background processes, scripts can implement error handling based on process success or failure. 4. **Resource Cleanup**: wait ensures that background processes have completed before script termination, preventing orphaned processes or incomplete operations. **Technical Details:** 1. **Built-in Command**: wait is implemented as a shell builtin in Bash, Zsh, and other shells, not as a separate executable. 2. **Process Relationship**: By default, wait only works with child processes of the current shell. In newer Bash versions (5.1+), the -f option allows waiting for any process. 3. **Signal Handling**: If the wait command itself is interrupted by a signal, it returns a status greater than 128, indicating the signal that interrupted it. 4. **Job Specification**: wait accepts various forms of job specifications, including job numbers (prefixed with %), job name patterns, and process IDs. **Shell-Specific Enhancements:** 1. **Bash 4.3+**: Introduced the -n option, which waits for any background job to complete and returns immediately when one finishes. 2. **Bash 5.1+**: Added the -f and -p options, enhancing wait's capabilities to monitor processes outside the direct parent-child relationship. 3. **Zsh**: Offers extended job control features that integrate with wait, such as waiting for jobs matching patterns or attributes. **Best Practices:** 1. **Storing Process IDs**: When starting background processes, store their PIDs (using $!) if you need to wait for specific processes later. ```bash process1 & PID1=$! process2 & PID2=$! # Do other work wait $PID1 $PID2 ``` 2. **Error Handling**: Always check the return status of wait to handle process failures appropriately. ```bash command & wait $! if [ $? -ne 0 ]; then echo "Command failed" exit 1 fi ``` 3. **Timeout Implementation**: For older Bash versions without -n, combine wait with timeout mechanisms if you need to limit waiting time. 4. **Signal Handling**: Consider setting up signal handlers if you need to gracefully handle interruptions during waits. **Performance Considerations:** 1. **Resource Usage**: wait itself consumes minimal resources, as it simply blocks the shell until the specified processes complete. 2. **Parallelism vs. Complexity**: While running processes in parallel with wait can significantly improve performance for IO-bound tasks, it increases script complexity and can make debugging more challenging. 3. **Large Process Counts**: When managing a large number of background processes, consider using wait with job control or batching techniques to prevent system overload. **Historical Context:** The wait command has been part of Unix shells since the early days, providing essential functionality for script writers to coordinate multiple processes. As shell scripting has evolved, wait has remained a key building block for creating more complex, parallel-capable scripts, particularly in system administration and batch processing contexts.

    Related Commands

    These commands are frequently used alongside wait or serve similar purposes:

    Use Cases

    Learn By Doing

    The best way to learn Linux commands is by practicing. Try out these examples in your terminal to build muscle memory and understand how the wait command works in different scenarios.

    $ wait
    View All Commands