Home > Back-end >  Taking sequentially output of multi ssh with bash scripting
Taking sequentially output of multi ssh with bash scripting

Time:11-09

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 user@$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?

CodePudding user response:

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 user@$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.

  • Related