-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
38 additions
and
23 deletions.
There are no files selected for viewing
This file contains 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
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!" |