How can I automatically change directory on ssh login?

Solution 1:

This works:

ssh server -t "cd /my/remote/directory; bash --login"

To create a directory if it doesn't exist:

ssh server -t "mkdir -p newfolder; cd ~/newfolder; pwd; bash --login"

If you don't add bash to the end of path then you exit after the cd comand runs. And If you don't add --login then your ~/.profile isn't sourced.

Solution 2:

  1. Login to your box
  2. Edit ~/.bash_profile
  3. On the end of the file add cd /path/to/your/destination
  4. Save it & exit
  5. Logout from box
  6. Login again and you should land on /path/to/your/destination

Solution 3:

cd is a shell builtin. LocalCommand is executed as:

/bin/sh -c <localcommand>

What you're looking to do can't really be accomplished via SSH; you need to modify the shell in some way, e.g. via bashrc/bash_profile.

<Editing almost a decade later...>

LocalCommand isn't what you want, anyway. That's run on your machine. You want RemoteCommand. Something like this worked for me:

Host example.net
  RemoteCommand cd / && exec bash --login
  RequestTTY yes

Solution 4:

More robust solution for the case when you need to ssh and override default .bashrc file. This is useful in cases when remote server environment has multiple docroots and used by multiple users.

alias ssh_myserver='ssh server_name -t "echo cd /path/to/desired/dir>/tmp/.bashrc_tmp; bash --rcfile /tmp/.bashrc_tmp"'

More detailed:

  1. First command creates .bashrc_tmp file in /tmp directory on the remote server with a content cd /path/to/dir
  2. Next command executes bash with config file specified in step 1. This allows to switch to desired dir and suppress default .bashrc.
  3. This whole command is wrapped as an alias, so on ssh client command prompt it can be called as ssh_myserver

Solution 5:

So I have searched a lot of websites (stackoverflow, this one) but did not find what I wanted. I ended up creating my own shell script. I am pasting it here. Also you can copy it a directory in the $PATH.

#!/bin/bash
ssh -t <username@hostname> "cd ~/$1; exec \$SHELL --login"

So after this. I do:

connect <foldername>

Note: You may need to log out and log in again after changing the path variable

Tags:

Ssh

Login