When I ssh into mycomputer from logincomputer, I would like to automatically cd into the current directory (the one from which the ssh command was executed) on mycomputer. In particular:

> cd /tmp/

Now /tmp/ is the current working directory.

> ssh mycomputer
> cd /tmp

I would like this to happen automatically with 1 command. Is this possible? Assume the directory structure is exactly the same on both computers.


3 Answers 3



Answered on Stack Overflow.

ssh -t xxx.xxx.xxx.xxx "cd /directory_wanted"

You could add this into a shell script:

ssh -t xxx.xxx.xxx.xxx "cd \$PWD; bash"

  • great, what does dirname and 0 do?
    – Alex
    Sep 16, 2013 at 20:00
  • also why not: ssh -t xxx.xxx.xxx.xxx "cd $(pwd); bash"
    – Alex
    Sep 16, 2013 at 20:26
  • @Alex I'm not very proficient in the way of BASH scripting, but I would assume $dirname $0 would return to path to where you currently are within the local system.
    – Kruug
    Sep 16, 2013 at 20:43
  • @Alex I got the second part from here: stackoverflow.com/questions/242538/… but it sounds like $(pwd) should be able to do the same thing.
    – Kruug
    Sep 16, 2013 at 21:02
  • ok, cool. i think the version you provide won't work.. that's the output of executing: >echo $(dirname $0) .
    – Alex
    Sep 16, 2013 at 21:05

I'd propose adding the following line to your .bashrc file:

sshcd() { ssh -t "$@" "cd '$(pwd)'; bash -l"; }

Then you can ssh into the remote host using

sshcd mycomputer

Passing ssh options also works as expected, e.g. to specify a different port:

sshcd mycomputer -p 2222` 

Break down how it works:

sshcd() {         \ # Define a function called sshcd
  ssh -t          \ # ssh and get remote pty although a command is given
    "$@"          \ # Pass all options from sshcd to ssh
    "cd '$(pwd)'; \ # Get the local directory using pwd, cd to it remotely
     bash -l";    \ # Then start a login shell on the remote host

The correct way to do this:

ssh -t xxx.xxx.xxx.xxx "cd \$PWD; bash"
  • using single quotes, no need to escape the variable
    – xeruf
    Feb 1, 2023 at 13:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .