BudiBadu Logo
Samplebadu

Bash by Example: Wait Command

Bash 5.0+

Synchronizing parallel execution by pausing script execution until specific background processes or all background jobs complete, capturing exit statuses of background tasks, implementing barrier synchronization patterns, and preventing race conditions in shell scripts.

Code

#!/bin/bash

echo "Launching parallel downloads..."

# Simulate downloads
(sleep 2; echo "Download A complete") &
pid1=$!

(sleep 4; echo "Download B complete") &
pid2=$!

(sleep 3; echo "Download C complete") &
pid3=$!

echo "Waiting for specific process A ($pid1)..."
wait $pid1
echo "Process A is done. Others might still be running."

echo "Waiting for the rest..."
wait

echo "All downloads finished!"

Explanation

The wait command is the synchronization primitive in Bash that allows parent scripts to coordinate with child processes. When you launch processes in the background using &, they run independently and asynchronously. If your script finishes and exits while background jobs are still running, those jobs might be terminated (depending on shell configuration) or become orphaned. The wait command allows the parent script to pause execution until specific child processes or all background jobs have completed.

You can use wait in several ways. If you provide a specific Process ID (e.g., wait $pid), execution pauses only until that particular process terminates. The exit status of the wait command itself becomes the exit status of that process, allowing you to check whether the background job succeeded or failed. This is crucial for error handling in scripts that depend on the results of parallel tasks.

If you run wait with no arguments, it blocks until all currently active background jobs spawned by the current shell have finished. This implements the "barrier" synchronization pattern: "Start tasks A, B, and C in parallel, but don't proceed to step D until everyone is finished." This is fundamental for workflows where subsequent operations depend on the completion and results of multiple parallel tasks. Some shells also support wait -n to return as soon as any single background job completes, enabling more sophisticated parallelism patterns.

Code Breakdown

6-11
We use subshells (...) to group commands and run them in the background together. Each $! captures the PID of its respective subshell for individual tracking.
16
wait $pid1 blocks execution here. Even if Download C finishes before A, the script will sit here until A is done.
20
The bare wait ensures that B and C are also finished before the script prints the final success message.