Interview Prep/Shell Scripting/Arrays, conditionals and loops

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.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Arrays, conditionals and loops