How to parallelize for-loop in bash limiting number of processes

bash 4.4 will have an interesting new type of parameter expansion that simplifies Charles Duffy’s answer.

#!/bin/bash

num_procs=$1
num_iters=$2
num_jobs="\j"  # The prompt escape for number of jobs currently running
for ((i=0; i<num_iters; i++)); do
  while (( ${num_jobs@P} >= num_procs )); do
    wait -n
  done
  python foo.py "$i" arg2 &
done

Leave a Comment