Bounded worker pools
Running every task at once can exhaust CPU, memory, descriptors or downstream capacity. A bounded worker pool limits the number of outstanding tasks and collects each status. A simple batch approach starts at most N children and waits for all before starting the next batch; it may leave capacity idle but is easy to reason about. A rolling pool can use wait -n with -p and a tracked PID set, but must handle completed children, interrupted waits and missing identifiers. Do not assume a nonzero wait result always means a child exited: check the returned identifier and context. Use deterministic task IDs and per-task files to avoid interleaved output. For fixed tasks, explicit waits preserve outcomes even when workers finish out of order. Use external timeouts only where supported, and remember that a timeout is not a universal descendant-cleanup guarantee. Examples here use finite synthetic work and at most two children at once. The second example reports an aggregate flag but deliberately finishes with a successful printf. A script that must fail on any failed task should explicitly exit with the aggregate flag.
Practical examples
Run each example as a separate script in a fresh noninteractive Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Limit a batch to two workers
pids=()failed=0for task in 1 2 3; do ( printf '%s\n' "$task" > "task-$task.txt" ) & pids+=("$!") if (( ${#pids[@]} == 2 )); then for pid in "${pids[@]}"; do wait "$pid" || failed=1; done pids=() fidonefor pid in "${pids[@]}"; do wait "$pid" || failed=1; done(( failed == 0 )) || exit 1cat task-1.txt task-2.txt task-3.txtExpected stdout:
123The parent collects every child at each batch boundary, remembers any failure, and reads results in task order only when all tasks succeed.
Aggregate failures
( exit 5 ) &a=$!( exit 0 ) &b=$!failed=0for pid in "$a" "$b"; do if wait "$pid"; then printf 'ok\n' else printf 'failed=%s\n' "$?" failed=1 fidoneprintf 'aggregate=%s\n' "$failed"Expected stdout:
failed=5okaggregate=1The loop reports both results and retains the aggregate flag. A real application would return that flag.
Bound a command using GNU timeout
timeout 1s bash -c 'printf "quick\n"'printf 'status=%s\n' "$?"Expected stdout:
quickstatus=0A command that finishes within the deadline retains its status. GNU timeout is an external utility, not a Bash keyword.
Common mistakes
Do not spawn unbounded tasks. Do not discard individual failures by waiting only for the last PID. Do not assume output order follows launch order.
Practice
Extend the two-worker batch example to five fixed tasks, with task 3 returning 8. Keep at most two outstanding children, record each status, and make the parent return nonzero if any task fails.
Next: Locks, FIFOs and race conditions