Skip to content

Commit

Permalink
Improve run_parallel.sh
Browse files Browse the repository at this point in the history
  • Loading branch information
unkhz committed Aug 5, 2024
1 parent d7a6599 commit 3592637
Showing 1 changed file with 38 additions and 23 deletions.
61 changes: 38 additions & 23 deletions run_parallel.sh
Original file line number Diff line number Diff line change
@@ -1,35 +1,50 @@
#!/bin/bash

# Array to store background process PIDs
pids=()

# Function to kill all child processes
cleanup() {
echo "Stopping all processes..."
for pid in "${pids[@]}"; do
kill -TERM "$pid" 2>/dev/null
done
exit 1
# Written by gemini-pro-1.5-exp-0801

# Function to execute a command and print its output with colorized label
run_command() {
local command="$1"
local label="$2"
local color_code=$((31 + $(($RANDOM % 7))))
echo -e "\e[${color_code}mRunning $label...\e[0m"
eval "$command"
local exit_code=$?
if [[ $exit_code -ne 0 ]]; then
echo -e "\e[31mError: Command '$label' failed with exit code $exit_code\e[0m"
fi
}

# Set up trap to catch SIGINT (Ctrl-C) and other termination signals
trap cleanup SIGINT SIGTERM
# Trap CTRL+C to kill all background processes
trap 'kill $(jobs -p); echo "Interrupted by CTRL+C"' INT

# Process command-line arguments
if [[ $# -lt 2 ]]; then
echo "Usage: $0 <label1> <command1> [<label2> <command2> ...]"
exit 1
fi

# Array to store label-color mappings
declare -A label_colors

# Function to run a task and prefix its output while preserving color
run_task() {
local task_name=$1
# Loop through arguments and run commands in parallel
for i in $(seq 1 2 $#); do
if [[ $((i % 2)) -eq 1 ]]; then
label="$1"
shift
# Use stdbuf to prevent line buffering and preserve colors
stdbuf -oL -eL "$@" 2>&1 | sed -u "s/^/[${task_name}] /"
}
command="$1"
shift

# Assign a color to the label if not already assigned
if [[ -z "${label_colors[$label]}" ]]; then
label_colors[$label]=$((31 + $(($RANDOM % 7))))
fi

# Run tasks in parallel
while (( "$#" )); do
run_task "$1" $2 &
pids+=($!)
shift 2
run_command "$command" "$label" &
fi
done

# Wait for all background processes to finish
wait

echo "All commands finished!"

0 comments on commit 3592637

Please sign in to comment.