Change default directory when I SSH to server

There are three ways to achieve this:

  • add cd /var/www/websites to the end of your .bash_profile. This is executed only for interactive logins (e.g. ssh).
  • add cd /var/www/websites to the end of your .bashrc. I use this one on our puppetmasters as I always want to be in /etc/puppet/environments/dkaarsemaker there instead of my homedir :-)
  • Change your homedirectory on the server to /var/www/websites (this is not really a good idea)

Warning! Try this on non-essential account first because if you make a mistake in the command you may lose an access to the remote system.


If you use keys for SSH login then you can change path by prepending command= to before a key in ~/.ssh/authorized_keys on your remote server. Example:

command="cd /var/www/websites ; /bin/bash -l" ssh-rsa AAA.....rest of the key

It is fine to generate and use multiple keys for the same user. One key on the server may contain the command the other may not - this way you select expected behaviour at login time. You can simply wrap it up with local ~/.ssh/config:

Host websites-my-host
    HostName <realhostname>
    IdentityFile ~/.ssh/<key1>  #on the server key with "command"
    User webmaster

Host my-host
    HostName <realhostname>
    IdentityFile ~/.ssh/<key2>  #on the server key without command
    User webmaster

This is what will occur:

local$ ssh websites-my-host
webmaster@realhostname:/var/www/websites$ _

or:

local$ ssh my-host
webmaster@realhostname:~$ _

Since OpenSSH 7.6, you can use the new RemoteCommand option to achieve that.

In your ~/.ssh/config:

Host websites-my-host
    HostName <realhostname>
    IdentityFile ~/.ssh/keyfile
    User webmaster
    RequestTTY force # check if this is necessary
    RemoteCommand cd /var/www/websites && bash -l

Openssh sshd by default accepts these environment variables from the client:

AcceptEnv LANG LC_*

You can use that to send a value from the local environment of the client to the server like this:

LC_CDPATH=/var/www/websites ssh -o SendEnv=LC_CDPATH user@server

You can place the SendEnv directive in ~/.ssh/config so you don't have to include it on the command line.

If you place the following in your ~/.profile (to only affect interactive logins use .profile, to affect all logins use .bashrc):

if [ "$LC_CDPATH" -a -d "$LC_CDPATH" ]; then
  cd "$LC_CDPATH";
fi

Then it will automatically change directory to the one specified in the environment variable when you login, if it is specified and if it is a directory.