I am using a script to connect to multiple servers. At the moment, I am using something like:

for SERVER in server1 server2 server3 ; do ssh $SERVER "my-command" ; done

I have to specify the (many) servers every time. I was wondering if there is a better way, for example if ssh has any possibility to define "groups of servers", so that I could refer to it as

for SERVER in $SERVERLIST ; do ssh $SERVER "my-command" ; done

or is this a bad idea, and should be done in bash instead?


You can set a variable $SERVERLIST yourself, in your shell.

$ SERVERLIST="server1 server2 server3"

You could also put them in a file and for loop through the file.

$ for SERVER in $(<servers.txt) ; do ssh $SERVER "my-command" ; done
  • The one thing that makes me nervous about your answer, is that it assumes that the server names don't contain any funny characters, which is probably fine in this case, but is something you need to watch out for in other cases. I would recommend passing a null separated list to xargs which is immune to this problem. – hildred Nov 23 '13 at 0:05
  • @hildred - if they're actual DNS hostnames then this isn't as big an issue as it is with file names. For example, new lines which can be used for file names cannot be used for hostnames. Also other weird characters such as &, ?, etc. are not legal either, so I think your point is moot here. – slm Nov 23 '13 at 1:11

Not the answer you're looking for? Browse other questions tagged or ask your own question.