1

I have a for loop:

for host in $(cat ./hosts)
do
   echo -e "$host"
   ssh -o "StrictHostKeyChecking no" $host "uptime" 2>/dev/null
   echo -e "\n"
done

and a while loop which is supposed to the the exact same job as the above for loop:

while read host
do
   echo -e "$host"
   ssh -o "StrictHostKeyChecking no" $host "uptime" 2>/dev/null
   echo -e "\n"
done <./hosts

hosts is a file located at the same place as the scripts containing for and while loop and it contains some host name of remote servers. The for loop prints the expected result (for all the hosts listed in the hosts file) but in case of while loop it only prints the first host's uptime and quits!

hosts file contains one host name per line.

The question is why the behavior of these two loops are different?

Vombat
  • 12,884

1 Answers1

2

The problem is that ssh reads from standard input, therefore it eats all your remaining lines. You can just connect its standard input to nowhere:

$ ssh -o "StrictHostKeyChecking no" $host "uptime" 2>/dev/null < /dev/null

References