1

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?

2
  • 1
    Put a valid shebang and paste your script at shellcheck.net for validation/recommendation. Commented Nov 8, 2022 at 6:01
  • Thanks for the warnings. I added shebang Commented Nov 8, 2022 at 6:20

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer, I solved the problem thanks to your answers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.