Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top
for account in ${accounts}
        `ssh -q id@server "touch EVENTS_${account}_${date}.log"`

Instead of doing ssh so many times, can I just do ssh and run the for loop and touch the files?

share|improve this question
up vote 3 down vote accepted

ssh allows you to execute multiple commands. Simply separate each command with a semi-colon.

command=": "
for account in ${accounts}
        command=$command"; touch EVENTS_${account}_${date}.log"
ssh -q id@server "$command"

All the ": " does is says "proceed to the next command." It's so you're not starting your command with a semi-colon.

Also, you don't need backticks around that command.

share|improve this answer

Run the loop on the remote machine.

ssh -q id@server "for account in ${accounts}; do touch EVENTS_\${account}_${date}.log; done"

Note that I assume that $accounts and $date don't contain any shell special characters ("$'()&;<>[\]`{|}~). In paricular, $accounts will be interpolated into the remote shell then interpreted there. If you need to protect special characters, you need to be more careful with the quoting:

q=\'\\\'\'  # '\'' effectively quotes a single quote inside single quotes
ssh -q id@server 'for account in '\'"${accounts//\'/$q}"\''; do touch "EVENTS_${account}_${date}.log"; done'

Alternatively, mount the remote filesystem with sshfs and work on it as you would locally.

mkdir mnt
sshfs id@server mnt
for account in ${accounts}; do touch "mnt/EVENTS_\${account}_${date}.log"; done
share|improve this answer
This is a little trickier because you have to escape the '$'. touch EVENTS_\${account}_${date}.log ought to work if ${date} is defined on the system calling ssh in the first place. Escaping prevents ${account} from being interpreted locally. – Chris Betti Feb 28 '12 at 2:59

Cluster ssh seems like the perfect tool for what you are trying to do.

ClusterSSH is a tool for making the same change on multiple servers at the same time. The 'cssh' command opens an administration console and an xterm to all specified hosts. Any text typed into the administration console is replicated to all windows. All windows may also be typed into directly.

This tool is intended for (but not limited to) cluster administration where the same configuration or commands must be run on each node within the cluster. Performing these commands all at once via this tool ensures all nodes are kept in sync.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.