Unable to loop with ssh

I read a file (iplist.txt) ine-by-line in a loop which has the list of all the server hostnames.

With each hostname read; I do ssh and fire multiple commands to gather information about that systemas shown below.

#!/bin/bash
while IFS='' read -r line || [[ -n "$line" ]]; do
    echo "Text read from file: $line"
    ssh user1@$line "df -h; kstat cpu_info|grep core_id|sort -u|wc -l"
done < "$1"

The loop shows the correct output for only the first server and then terminates.

How can I make the loop traverse the entire list of servers(hostnames) ?

That may sounds strange, but as matter of fact: ssh eats your loop arguments here. This specific implementation of a loop does not work with an ssh-command involved. Use a method like this instead:

for line in $(cat "$1"); do
          echo "Text read from file: $line"
       ssh user1@$line "df -h; kstat cpu_info|grep core_id|sort -u|wc -l"

done

This way the whole arguments are read at the begin of the loop and ssh is prevented from slurping up whole stdin.

I'm getting error using your suggestion:

./testssh.sh: line 9: syntax error near unexpected token `echo'
./testssh.sh: line 9: `          echo "Text read from file: $line"'

------ Post updated at 08:00 AM ------

Nevermind, the do was missing in the for loop. Thank you ... it now works !!

Yes it does. It requires a workaround but it does.

Also, that's a dangerous use of backticks and there's never any good reason to use it.

#!/bin/bash
while IFS='' read -u5 -r line || [[ -n "$line" ]]; do
    echo "Text read from file: $line"
    ssh user1@$line "df -h; kstat cpu_info|grep core_id|sort -u|wc -l"
done 5< "$1"
1 Like