LinuxCommandLibrary

wait

Wait for child processes to complete

TLDR

Wait for a process to finish given its process ID (PID) and return its exit status

$ wait [pid]
copy

Wait for all processes known to the invoking shell to finish
$ wait
copy

Wait for a job to finish
$ wait %[job_number]
copy

Display help
$ wait --help
copy

SYNOPSIS

wait [n...]

PARAMETERS

n
    Specifies the process ID (PID) of a background process to wait for. If n is not provided, wait waits for all currently active background processes to complete.

DESCRIPTION

The wait command in Linux is a built-in shell command that suspends execution of the current shell script or interactive session until a specified background process completes or until all background processes complete. It is primarily used for synchronization, ensuring that dependent tasks are executed in the correct order. This is crucial when a script relies on the output or completion of a backgrounded process before continuing.

Without wait, the shell would continue executing subsequent commands immediately after launching a process in the background, potentially leading to race conditions or unexpected behavior. wait offers the ability to check the exit status of waited-on processes, reporting error codes, and facilitating error handling within scripts. It is indispensable for controlling the flow of complex shell scripts involving asynchronous operations.

CAVEATS

If you specify a PID that doesn't exist or has already completed, wait returns immediately with exit status 0.
wait only works for child processes of the current shell.
Backgrounded shell pipelines are also waited for as a unit.

EXIT STATUS

The wait command returns the exit status of the last process waited for. If a specific process ID is given and that process ID is not valid, wait returns 127. If a signal terminated any waited for process, the exit status of wait can be 128+signal

ERROR HANDLING

Error codes are valuable for handling errors inside shell scripts. You can check the exit code with $? variable after calling wait and decide what to do based on exit code

SEE ALSO

jobs(1), kill(1), bg(1), fg(1)

Copied to clipboard