Created
January 10, 2020 20:40
-
-
Save mdelillo/b3bdf7c646d302a9da74c8f4303bf428 to your computer and use it in GitHub Desktop.
Function to run a command in parallel batches
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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