Bash: Looping Over Stored Hostnames, Executing Commands via SSH on Those Hosts

bashbash-scriptingcygwin;opensshssh

I store in a file named ssh_hosts.txt a list of hostnames. In a shell script, I loop over the hostnames in ssh_hosts.txt and execute a command on the named host via SSH. The shell script is shown below.

The problem is that the script exits after processing the first host. But if I do something other than execute a command on the named host via ssh, the script will run to completion.

In the example below, I've commented out the call to ssh and replaced it with a simple echo of the current host name. This will run to completion.

I am executing this script from a bash shell running under the following Cygwin version on Windows 7:

$ uname -a
CYGWIN_NT-6.1 myHostname 1.7.16(0.262/5/3) 2012-07-20 22:55 i686 Cygwin

These SSH versions are involved:

$ ssh -V
OpenSSH_6.0p1, OpenSSL 1.0.1c 10 May 2012

$ ssh myUsername@remoteHost 'ssh -V'
myUsername@remoteHost password:
OpenSSH_6.7p1 Debian-5+deb8u3, OpenSSL 1.0.1t  3 May 2016

Here is the shell script:

#!/bin/bash

if [[ $# -ne 1 ]]; then
   echo "Usage: $(basename $0) <user name>"
   exit 1
fi

USER="$1"

while IFS='' read -r ssh_host || [[ -n "$ssh_host" ]];
do
   # This line will execute for all hosts listed in ssh_hosts.txt.
   echo $ssh_host

   # This line will execute for *only the first* host in ssh_hosts.txt.
   # ssh $USER@$ssh_host 'echo $(whoami)@$(hostname)'
done < ssh_hosts.txt

How may I get this shell script to execute over all hosts in ssh_hosts.txt rather than just over the first host?

Best Answer

I think you are making it too complicated:

for ssh_host in $(cat ssh_hosts.txt)
do
   echo $ssh_host
   ssh $user@$ssh_host ....
done

Also, search github for gsh, which is a perl program that will do more if you do this often.

Related Question