Background Jobs and Parallel Processing
Manages background jobs with &, wait, jobs, and process control for parallel task execution and synchronization in Bash scripts.
Code
#!/usr/bin/env bash
set -uo pipefail
# Launch background jobs
echo "Starting parallel jobs..."
for i in 1 2 3 4 5; do
(
echo "Job $i started"
sleep $(( RANDOM % 3 + 1 ))
echo "Job $i completed"
) &
done
# Wait for all background jobs
wait
echo "All jobs completed"
# Capture background job output
declare -A results
for i in 1 2 3; do
(
result=$(( i * i ))
echo "$result" > "/tmp/job-$i-$$"
) &
done
wait
for i in 1 2 3; do
results[$i]=$(cat "/tmp/job-$i-$$" 2>/dev/null)
rm -f "/tmp/job-$i-$$"
done
echo "Results: ${results[1]}, ${results[2]}, ${results[3]}"
# Parallel with job limit
max_jobs=3
running=0
process_item() {
local item=$1
echo "Processing $item..."
sleep 1
echo "Done: $item"
}
for item in {1..10}; do
process_item "$item" &
((running++))
if (( running >= max_jobs )); then
wait -n
((running--))
fi
done
wait
echo "All parallel work done"Inside the snippet
The work is delegated to sleep, declare, rm, process_item and wait, chained so each stage’s output feeds the next.
A helper function (process_item) keeps the repeated logic out of the main flow.
The key statements that remain
for i in 1 2 3 4 5; do
(
echo "Job $i started"
sleep $(( RANDOM % 3 + 1 ))
echo "Job $i completed"
) &
for i in 1 2 3; do
(
result=$(( i * i ))
echo "$result" > "/tmp/job-$i-$$"
) &
for i in 1 2 3; do
results[$i]=$(cat "/tmp/job-$i-$$" 2>/dev/null)
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Which external commands does the script rely on?
- `sleep`, `declare`, `rm`, `process_item`, `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.