Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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

I am implementing an automated backup scheme so I created a shell script which first creates SQL dumps for all MySQL databases, then retrieves all websites from the /var/www directory of a remote server. The latter is working as I am using rsync to get the remote files.

However, the MySQL dumps being retrieved are the ones from the local server which is not what I want. I want to get the SQL dumps from the remote server as well.

I have a tunnel between the local and remote server which I can connect to without using any password (I added the public key to the authorized_hosts), so I tried to add the following code to the script:


I then attempted to retrieve the SQL dumps and exited from the remote server. However this does not work as I still have to enter exit manually in the terminal for the SQL dumps to be retrieved from the remote host. I don't know why this is happening. This is what the script is trying to do:

//connect to remote server 

//retrieve SQL dumps 
//code to retrieve...

//exit from remote server 

//use rsync to get remote files of /var/www from local server (working)

Is there a way to connect to the remote host AND run the script's code on THAT remote host?

share|improve this question
up vote 4 down vote accepted

Just add the command you want to run to the end of the ssh command line. So something like this:

ssh /path/to/script

will run /path/to/script on the remote machine.

share|improve this answer
So simple! yet I couldn't find it! Thanks a lot! – seedg Jun 30 '11 at 8:24

If it's one command, use ssh user@host remotecommand. For example:

ssh user@dbhost "mysqldump" > dumpfile

Note that redirections take place locally (unless you put them inside quotes), so dumpfile will be created on the local computer.

The remotecommand argument is in fact passed to the default shell of user, so you can use stuff like a; b && c and if/while statements. But it's wiser to put them in a second script file instead (in the db server).

share|improve this answer

Your Answer


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

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