Skip to content

Instantly share code, notes, and snippets.

@mdelillo
Created January 10, 2020 20:40
Show Gist options
  • Save mdelillo/b3bdf7c646d302a9da74c8f4303bf428 to your computer and use it in GitHub Desktop.
Save mdelillo/b3bdf7c646d302a9da74c8f4303bf428 to your computer and use it in GitHub Desktop.
Function to run a command in parallel batches
#!/usr/bin/env bash
loop() {
total_runs=$1
runs_per_loop=$2
shift
shift
int_regex='^[0-9]+$'
if ! [[ $total_runs =~ $int_regex ]] ; then
echo "Usage: loop <total runs> <runs per loop> <command>"
return
fi
if ! [[ $runs_per_loop =~ $int_regex ]] ; then
echo "Usage: loop <total runs> <runs per loop> <command>"
return
fi
number_of_loops=$((total_runs / runs_per_loop))
remainder=$((total_runs % runs_per_loop))
if [[ "$total_runs" -gt "$runs_per_loop" ]]; then
for loop in $(seq 0 $((number_of_loops - 1))); do
for loop_run_num in $(seq 1 $runs_per_loop); do
$@
done
wait 2>/dev/null
done
fi
if [[ "$remainder" -ne 0 ]]; then
for loop_run_num in $(seq 1 $remainder); do
$@
done
wait 2>/dev/null
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment