Restore Your SSH Session Working Directory

The Problem

I want to login to a remote Linux machine via SSH and to be in the same directory I was before my last log out.

The Solution

Since my login shell is bash, I present this solution in bash, but you can adapt it for your favorite shells. This tip relies on the two special files ~/.bash_profile and ~/.bash_logout. When a user logs out of a Linux system, the login shell (bash in this case) executes the ~/.bash_logout file, which is where we save our working directory:

# Contents of .bash_logout
rm -f $LASTDIRFILE
echo cd $PWD > $LASTDIRFILE

Likewise, we a user logs in, bash execute .bash_profile, so we put the instruction to restore the working directory there:

# Contents of .bash_profile
# ...

# Restore last directory
export LASTDIRFILE=~/.lastdir
test -f $LASTDIRFILE && source $LASTDIRFILE

Conclusion

The ~/.bash_logout is a wonderful file for saving your session’s details and its counterpart, ~/.bash_profile, is good for restoring them.

One thought on “Restore Your SSH Session Working Directory

  1. Christian Weiske

    Thanks for the bash_logout pointer.
    Your script does not work for directories with spaces, and is a bit unsecure as I wouldn’t expect a “lastdir” file to contain actual commands. Storing it under ~/.config/ is probably also better than cluttering ~.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s