Parallel Jobs Wait And Collect
Run background jobs in parallel with a concurrency limit and wait for all to complete collecting exit statuses.
Code
#!/usr/bin/env bash
set -uo pipefail
MAX_JOBS=4
pids=()
run_task() {
local id=$1
sleep $((RANDOM % 5 + 1))
echo "Task ${id} done"
}
for i in $(seq 1 20); do
run_task "$i" &
pids+=($!)
if [[ ${#pids[@]} -ge ${MAX_JOBS} ]]; then
wait "${pids[0]}"
pids=("${pids[@]:1}")
fi
done
wait
echo "All tasks completed"How the snippet works
The work is delegated to sleep, run_task and wait, chained so each stage’s output feeds the next.
A helper function (run_task) keeps the repeated logic out of the main flow.
Statements that decide the outcome
sleep $((RANDOM % 5 + 1))
for i in $(seq 1 20); do
run_task "$i" &
Interactive Tools for This Topic
FAQ
- Which external commands does the script rely on?
- `sleep`, `run_task`, `wait` must be available on the PATH environment variable; everything else is shell built-in syntax.
Report a problem with this exampleOpens a pre-filled issue on GitHub.