How do you make a script process items in parallel with a concurrency limit, in pure Bash?
AdvancedConceptArrays, conditionals and loops
Answer
max_jobs=4 rc=0
for host in "${hosts[@]}"; do
while (( $(jobs -rp | wc -l) >= max_jobs )); do
wait -n || rc=1 # Bash 4.3+: wait for any one job
done
deploy_host "$host" &
done
while (( $(jobs -rp | wc -l) > 0 )); do wait -n || rc=1; done
exit "$rc"
xargs -P 4 or GNU parallel are simpler for one-command-per-item. Always capture per-job failures; plain wait returns 0 even if a job failed.
More on Arrays, conditionals and loops
How do you declare, populate and iterate an indexed array?BeginnerWhat is the difference between `"${arr[@]}"` and `"${arr[*]}"`?IntermediateHow do associative arrays work and what are they good for in DevOps scripts?IntermediateHow do you read a command's output into an array correctly?IntermediateWhat is the difference between `[ ]`, `[[ ]]` and `(( ))`?BeginnerWhy does `[ $var = "prod" ]` fail when `var` is empty or contains spaces?Intermediate