Topics: Red Hat / Linux, 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




If you found this useful, here's more on the same topic(s) in our blog:


UNIX Health Check delivers software to scan Linux and AIX systems for potential issues. Run our software on your system, and receive a report in just a few minutes. UNIX Health Check is an automated check list. It will report on perfomance, capacity, stability and security issues. It will alert on configurations that can be improved per best practices, or items that should be improved per audit guidelines. A report will be generated in the format you wish, and the report includes the issues discovered and information on how to solve the issues as well.

Interested in learning more?