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

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.

share|improve this question
..and what happens if the directory only exists on mycomputer and not logincomputer? –  heavyd Sep 16 '13 at 19:54
edited to reflect your comment –  Alex Sep 16 '13 at 19:57

3 Answers 3

up vote 2 down vote accepted

Answered on Stack Overflow.

ssh -t "cd /directory_wanted"

You could add this into a shell script:

ssh -t "cd \$PWD; bash"

share|improve this answer
great, what does dirname and 0 do? –  Alex Sep 16 '13 at 20:00
also why not: ssh -t "cd $(pwd); bash" –  Alex Sep 16 '13 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 '13 at 20:43
@Alex I got the second part from here:… but it sounds like $(pwd) should be able to do the same thing. –  Kruug Sep 16 '13 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 '13 at 21:05

The correct way to do this:

ssh -t "cd \$PWD; bash"
share|improve this answer

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
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.