LinuxCommandLibrary

wait

Wait for background processes to complete

TLDR

Wait for all background jobs to complete

$ wait
copy
Wait for a specific job by PID
$ wait [pid]
copy
Wait for multiple PIDs
$ wait [pid1] [pid2]
copy
Wait for a job by job spec
$ wait %1
copy
Get exit status of waited process
$ command & wait $!; echo "Exit status: $?"
copy

SYNOPSIS

wait [pid|jobspec...]

DESCRIPTION

wait is a shell builtin that pauses execution until specified background processes complete. It returns the exit status of the waited-for process.
When given a PID, wait blocks until that process terminates. With a job specification (%1, %2, etc.), it waits for that specific job. Without arguments, it waits for all child processes.
This is essential for scripts that spawn background processes and need to synchronize their completion or check their exit status.
The special variable $! contains the PID of the last background process, commonly used with wait: command & pid=$!; wait $pid

PARAMETERS

pid

Process ID to wait for
jobspec
Job specification (e.g., %1, %+, %-)
Without arguments, wait for all background processes.

EXAMPLES

$ # Run commands in parallel, then wait
command1 &
command2 &
command3 &
wait  # Wait for all three

# Wait and check exit status
long_task &
pid=$!
wait $pid
if [ $? -eq 0 ]; then
    echo "Success"
fi
copy

CAVEATS

Wait only works with child processes of the current shell. You cannot wait for arbitrary processes started by other shells or users.
In bash, wait -n (wait for any single job) is useful for processing results as jobs complete, but this option isn't available in all shells.
Exit status is only available immediately after wait returns. Calling wait again on the same PID may return different results.

SEE ALSO

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

> TERMINAL_GEAR

Curated for the Linux community

Copied to clipboard

> TERMINAL_GEAR

Curated for the Linux community