Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

This question already has an answer here:

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?

share|improve this question
add comment

marked as duplicate by Gilles, rahmu, slm, jasonwryan, Anthon Nov 23 '13 at 3:44

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1 Answer

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
share|improve this answer
    
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
add comment

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