Taking sequentially output of multi ssh with bash scripting

Issue

I’m wrote a bash script and I don’t have a chance to download pssh. However, I need to run multiple ssh commands in parallel. There is no problem so far, but when I run ssh commands, I want to see the outputs sequentially from the remote machine. I mean one ssh has multiple outputs and they get mixed up because more than one ssh is running.

#!/bin/bash
pid_list=""
while read -r list
do
    ssh [email protected]$list 'commands'&
    c_pid=$!
    pid_list="$pid_list $c_pid"
done < list.txt

for pid in $pid_list
do
    wait $pid
done

What should I add to the code to take the output unmixed?

Solution

The most obvious way to me would be to write the outputs in a file and cat the files at the end:

#!/bin/bash

me=$$
pid_list=""
while read -r list
do
    ssh [email protected]$list 'hostname; sleep $((RANDOM%5)); hostname ; sleep $((RANDOM%5))' > /tmp/log-${me}-$list &
    c_pid=$!
    pid_list="$pid_list $c_pid"
done < list.txt

for pid in $pid_list
do
    wait $pid
done

cat /tmp/log-${me}-*
rm  /tmp/log-${me}-* 2> /dev/null

I didn’t handle stderr because that wasn’t in your question. Nor did I address the order of output because that isn’t specified either. Nor is whether the output should appear as each host finishes. If you want those aspects covered, please improve your question.

Answered By – Mark Setchell

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published