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

I would like to be able to automatically run a command on a remote host each time I log into that host, but within the current interactive SSH session.

Something like

ssh user@remotehost [run do.sh]

where do.sh does a couple of housekeeping tasks and then reattaches to a screen session (currently I run do.sh manually after logging into the host).

I don't want to add it to .bashrc because I login to this host from other machines and I don't want do.sh to run when I do login from there so I need it to be optional.

share|improve this question
why you don't simply run ssh user@remotehost /path/to/do.sh ? If it works, you can even alias it in .ssh/config or your personnal .bashrc – Coren Feb 3 '12 at 9:50
So you want to run "do.sh" when you log in to remotehost from somewhere, but not when you log in to remotehost from somehwere else? Which hosts do you connect from should trigger "do.sh", and which others shouldn't? – Mat Feb 3 '12 at 10:09
Yes, I want to run it sometimes, but not all the time, the reason for this is that I have a keyboard shortcut from a launcher on my Mac that gives me what I want most of the time. I hit a shortcut and I want to ssh into the box and then reattach to a screen session, but I don't want to do that if I use a regular terminal like "ssh user@host". The solution mentioned below by Patkos does exactly what I need. – Jim Farkas Feb 3 '12 at 11:13
Accept his answer then ;) – AD7six Feb 3 '12 at 11:36
up vote 9 down vote accepted

You could try something like this:

ssh server -t "do.sh; bash --login"

as suggested here: http://serverfault.com/questions/167416/change-directory-automatically-on-ssh-login

Or you could try using the 'LocalCommand' option in sshd_conf (or ~/.ssh/config) as described in the official man page: http://unixhelp.ed.ac.uk/CGI/man-cgi?ssh+1

share|improve this answer
Thanks so much!! ssh server -t "/home/user/do.sh; bash --login" worked for me. köszönöm szépen! – Jim Farkas Feb 3 '12 at 11:07
Szivesen (You are welcome) – Patkos Csaba Feb 3 '12 at 11:57

One part of the puzzle: assuming OpenSSH, the ssh client will set the following environment variable:

SSH_CONNECTION Identifies the client and server ends of the connection. The variable contains four space-separated values: client IP address, client port number, server IP address, and server port number.

So you can use this information to find out where your connection comes from.

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.