Created
December 13, 2024 08:40
-
-
Save pcreux/30536d5dca6c6764f516afeee3ebbd61 to your computer and use it in GitHub Desktop.
Ruby script to run commands in parallel, print the output with different colors, and provide a summary.
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
#!/usr/bin/env ruby | |
# Run commands in parallel, print the output with different colors, | |
# and provide a summary. | |
COMMANDS = [ | |
"curl -v www.google.com", | |
"curl -v www.yahoo.com", | |
"dig www.google.com", | |
"hoo", | |
"dig www.yahoo.com", | |
] | |
COLORS = %w[31m 32m 33m 34m 35m 36m 91m 92m 93m 94m 95m 96m] | |
require 'open3' | |
def run_command(command, color: COLORS.sample) | |
Open3.popen3(command) do |_stdin, stdout, stderr, wait_thr| | |
# Process stdout | |
stdout_thread = Thread.new do | |
stdout.each_line do |line| | |
puts "\e[#{color}#{command}\e[0m: #{line.chomp}" # Prefix with the command and print | |
end | |
end | |
# Process stderr | |
stderr_thread = Thread.new do | |
stderr.each_line do |line| | |
warn "\e[#{color}#{command} (stderr)\e[0m: #{line.chomp}" # Prefix with the command and print | |
end | |
end | |
# Wait for the threads to finish | |
stdout_thread.join | |
stderr_thread.join | |
# Wait for the process to finish | |
wait_thr.value # exit_status | |
end | |
end | |
# Run each command in a separate process | |
processes = COMMANDS.each_with_index.map do |command, index| | |
fork do | |
color = COLORS[index % COLORS.size] | |
status = run_command(command, color: color) | |
if status.success? | |
exit 0 | |
else | |
exit 1 | |
end | |
end | |
end | |
# Wait for all processes to finish | |
statuses = processes.map do |pid| | |
Process.wait(pid) | |
$? | |
end | |
puts | |
# Check the exit status of each process | |
COMMANDS.each_with_index do |command, index| | |
status = statuses[index] | |
if status.success? | |
puts "✅ #{command}" | |
else | |
puts "❌ #{command}" | |
end | |
end | |
if statuses.all?(&:success?) | |
exit 0 | |
else | |
exit 1 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment