Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

I often want to ssh into a different server, but retain my working directory. (All our servers have the same NFS and thus the same directory path usually exists on all servers.) Is it possible to do this?

share|improve this question

3 Answers 3

If the remote server has been preconfigured (in sshd_config) with

AcceptEnv CURRENT_DIR

And you include

cd "$CURRENT_DIR"

as the last line in the remote servers' ~/.bashrc, you can connect with

CURRENT_DIR="$PWD" ssh user@host -o SendEnv=CURRENT_DIR

It's a workaround, but it'll...work.

share|improve this answer

I found a nice solution on superuser.com which is much like @adaptr's solution but without manually setting the environment variable.

By creating an alias for ssh you can set that variable automatically:

alias ssh='env SSH_PWD="$PWD" /bin/ssh'

Configure ssh in ~/.ssh/config to send the SSH_PWD variable:

For a single host add this:

Host myhost
  SendEnv SSH_PWD

Or for all hosts add this to the bottom of the file:

SendEnv SSH_PWD

And on the remote server in your .profile or .bashrc:

if [ -n "$SSH_PWD" ] && [ -d "$SSH_PWD" ]; then
   cd "$SSH_PWD"
   unset SSH_PWD
fi
share|improve this answer

If you can't change the remote servers's configuration and use key-based SSH logins with an ssh-agent (thus sparing you to have to enter your password or key passphrase every time), another hackish approach:

On your local machine, create a wrapper script which is in your path (eg. /usr/local/bin/cdssh)

#!/bin/bash
TMPFILE="/tmp/$(basename $0).$$.tmp"
echo "cd `pwd`" > $TMPFILE
scp -q $TMPFILE $1:~/.cwdfile
ssh $@
rm $TMPFILE

On the remote machine, add the following part to your ~/.bashrc or ~/.profile:

if [ -f ~/.cwdfile ]; then
   cd ~/.cwdfile
   rm ~/.cwdfile
fi

Obviously, this is a wild hack, but it works.

share|improve this answer

Your Answer

 
discard

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.