Home » Questions » Computers [ Ask a new question ]

Keeping working directory across ssh

Keeping working directory across ssh

I have a large number of Linux machines all of which mount my home directory over NFS. If I'm in ~/foo/bar/baz I'd like to be able to ssh to another machine and automatically start using that as my working directory. There doesn't appear to be an easy way to do this; I can think of some hacky ones but would like to check before trying them.

Asked by: Guest | Views: 34
Total answers/comments: 2
Guest [Entry]

"Check out SendEnv (in ssh_config) and AcceptEnv (in sshd_config). You might be able to send PWD; though at the receiving end just getting PWD won't be enough to make the new shell start in the desired directory.

So you could do something like:

put SendEnv SSH_PWD in your ssh_config and AcceptEnv SSH_PWD in your sshd_config.
Add the following to your .profile or .bash_profile:


alias ssh='env SSH_PWD=""$PWD"" /bin/ssh'
if [ -n ""$SSH_PWD"" ]; then
cd ""$SSH_PWD""
unset SSH_PWD
Guest [Entry]

"I don't know if this is considered ""Hacky"" or not, but here's an idea:

Since your homedir is shared across all servers, the same profile will be executed at login. You could have your .profile do something like this at the bottom:

CURR_DIR=$(cat ~/.current_dir)
if [[ -n $CURR_DIR ]] && [[ -d $CURR_DIR ]]; then

Then, alias your SSH command to run a script that will put your current dir into your ~/.current_dir file before running the SSH command, and remove the ~/.current_dir file once the SSH connection has been closed.

I have not tested this, but it could be a starting point.

Good luck!"