Bash Wait and Parallel Jobs
Bash wait -n is a wait that returns when the next background job finishes. It lets a script reuse a free slot instead of waiting for every job at once.
wait -n returns after the first finisher
Two jobs sleep for different times. The first line prints after the shorter job ends, before the final wait collects the rest.
(sleep 0.3) &
(sleep 0.1) &
wait -n
echo "one finished"
wait
echo "all finished"wait -n reports the finisher's status
The shorter job exits with status 3, and the longer job would exit with 5. The printed status proves wait -n reported the first finisher.
(sleep 0.5; exit 5) &
(sleep 0.1; exit 3) &
wait -n
echo "first status: $?"
wait
echo "all done"Two slots for four jobs
The loop starts at most two jobs before a wait -n frees a slot. The final count proves all four jobs completed.
max=2
running=0
for i in 1 2 3 4; do
( printf 'done %s\n' "$i" > "result.$i" ) &
running=$((running + 1))
if (( running >= max )); then wait -n; running=$((running - 1)); fi
done
wait
count=0
for f in result.*; do count=$((count + 1)); done
echo "results: $count"Example
max=2
running=0
for i in 1 2 3 4; do
( printf 'item %s ready\n' "$i" > "out.$i" ) &
running=$((running + 1))
if (( running >= max )); then wait -n; running=$((running - 1)); fi
done
wait
for i in 1 2 3 4; do cat "out.$i"; doneKey points
- wait -n: returns as soon as one background job finishes, while the others keep running.
- Status: the exit status of wait -n is the exit status of the job that just finished.
- Slot control: after wait -n frees a slot, the script can start a new job in its place.
- Plain wait: wait with no argument waits for every background job before moving on.
- Order: wait -n reports jobs in finish order, not start order, so results must be collected by name, not by timing.
- Counting: a loop that calls wait -n once per job collects every job exactly once.
In this example, the loop starts jobs while keeping at most two running. Each time the running count reaches the limit, wait -n frees one slot before the next job starts. The final wait collects the last jobs. Reading the result files in number order gives a fixed output order.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A script runs four jobs with two slots. After wait -n returns, what may the script safely do?