Bash ≥4.3, wait -n:
#!/bin/bash
max_nb_jobs=10
for i in file*; do
while mapfile -t < <(jobs -pr) && ((${#MAPFILE[@]}>=max_nb_jobs)); do
wait -n
done
{
} &
done
wait
wait -n, - :
#!/bin/bash
set -m
max_nb_jobs=10
sleep_jobs() {
local n=$1
while mapfile -t < <(jobs -pr) && ((${#MAPFILE[@]}>=n)); do
coproc read
trap "echo >&${COPROC[1]}; trap '' SIGCHLD" SIGCHLD
[[ $COPROC_PID ]] && wait $COPROC_PID
done
}
for i in files*; do
sleep_jobs "$max_nb_jobs"
{
} &
done
wait
The advantage of this kind is that we make no assumptions about the time taken to complete the work. A new job starts as soon as there is room for it. In addition, all this is pure Bash, therefore it does not rely on external tools and (perhaps more importantly), you can use the Bash environment (variables, functions, etc.) without exporting them (arrays cannot be easily exported like this, what could be a huge pro).
source
share