Skip to content

Instantly share code, notes, and snippets.

@gautamkrishnar
Last active July 17, 2023 04:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gautamkrishnar/608f10b87fcd1e0907c8470f72565836 to your computer and use it in GitHub Desktop.
Save gautamkrishnar/608f10b87fcd1e0907c8470f72565836 to your computer and use it in GitHub Desktop.
A zero dependency shell script for running 2 commands in paralell, combining their output into a single stdout. Also prepending a static string to differentiate the output.

Concurrent Command Execution with Unified Output

This lightweight shell script demonstrates running two commands in parallel while combining their outputs into a single stdout. The script also prepends a static string to differentiate the output of each command. This solution requires zero external dependencies, making it efficient and easy to use.

run.sh

#!/bin/bash

# replace command1 and command2 with command you need to execute
# replace the Server1 and Server2 with static message you want to show

mkfifo server1_output server2_output

command1 > server1_output 2>&1 &
command2 > server2_output 2>&1 &

{
    while read -r line_server1 <&3; do
        echo "[Server1] $line_server1"
    done &
    while read -r line_server2 <&4; do
        echo "[Server2] $line_server2"
    done
} 3<server1_output 4<server2_output

wait

rm server1_output server2_output

Example

run1.sh
#!/bin/bash
while true;do echo "Hi from run 1"; done;
run2.sh
#!/bin/bash
while true;do echo "Hi from run 2"; done;

output

[Server1] Hi from run 1
[Server1] Hi from run 1
[Server1] Hi from run 1
[Server2] Hi from run 2
[Server1] Hi from run 1
[Server1] Hi from run 1
[Server1] Hi from run 1
[Server2] Hi from run 2
[Server1] Hi from run 1
[Server1] Hi from run 1
[Server1] Hi from run 1
[Server2] Hi from run 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment