Topics: Red Hat, Scripting

Bash scripting: SSH breaks out of while-loop

If you use a bash shell script that does an ssh command within a while-loop, you may encounter that the ssh command will break out of the while-loop, and that the script doesn't complete all the intended ssh commands. An example of a script is below:

# cat hostsfile
server1
server2
# cat script
cat hostsfile | while read server ; do
        echo $server
        ssh $server uptime
done
# ./script
server1
 16:19:22 up 11 days, 22:30,  0 users,  load average: 0.00, 0.01, 0.05
As you can see in the example above; the script should run a ssh command for all files in the file "hostsfile". Instead, it stops after the first one.

This can be very easily resolved, by adding the "-n" option for the ssh command, as follows:
# cat script
cat hostsfile | while read server ; do
        echo $server
        ssh -n $server uptime
done
# ./script
server1
 16:19:22 up 11 days, 22:30,  0 users,  load average: 0.00, 0.01, 0.05
server2
 15:20:56 up 11 days, 22:32,  0 users,  load average: 0.00, 0.00, 0.00

Number of results found for topic Scripting: 1.
Displaying results: 1 - 1.