Skip to content

wait Command Cheat Sheet

wait halts script execution until a background process (PID) or job completes.


Synopsis

wait [PID]
wait [jobspec]

Basic Usage

Wait for Last Background Job

sleep 10 &
wait $!
echo "Done"
$! is the PID of the last background command.

Wait for Specific PID

process_command &
PID=$!
# Do other stuff...
wait $PID

Parallel Processing Pattern

Run multiple jobs and wait for all to finish.

#!/bin/bash

# Start 3 background jobs
sleep 5 &
sleep 8 &
sleep 3 &

echo "Waiting for all jobs..."
wait
echo "All jobs finished!"

Obtaining Exit Status

wait returns the exit code of the process it waited for.

command_that_fails &
PID=$!
wait $PID
STATUS=$?

if [ $STATUS -ne 0 ]; then
    echo "Background job failed with status $STATUS"
fi

Notes

  • Interactive: In an interactive shell, wait without arguments waits for all background jobs started in that shell.