SSH login: automatically goto last directory visited?
During my multitasking days, sometimes I will be booted off of an SSH session for one reason or another (idle timeouts, etc), while I am working on another task. When I return to the terminal, I will find myself back at localhost, needing to SSH back to the server. Once back at the server, I'm always in my ~
home directory by default and I need to navigate back to the directory I was at last (if I can remember it) in order to continue working.
Is it possible to automatically return to the last directory I was working in when I login?
I was thinking a homebrew solution would be aliasing cd
to change directories but also save that directory into some environment variable, and then changing to that directory in my .bash_profile
.
But is there any sort of functionality like this already in Linux?
Instead of solving the cd
persistence problem, you should consider solutions to resume your shell session.
-
tmux
- Inside SSH, run
tmux
to start a new session - If disconnected, SSH in again, and run
tmux attach
to resume the session - Inside a
tmux
session, you can press CtrlB, then D to detach
- Inside SSH, run
-
screen
- Inside SSH, run
screen
to start a new session - If disconnected, SSH in again, and run
screen -r
to resume the session - Inside a
screen
session, you can press CtrlA, then D to detach
- Inside SSH, run
-
mosh
-
mosh
is an SSH replacement that runs over UDP and is designed to be resistant to network disruptions
-
No need for any 3rd party software or app, just use built-in linux
- when log out, assign $PWD (last dir) to a temporary var before logout:
echo $PWD >~/lastdir
- when log in, cd that dir at ~/.bash_profile:
cd $(<~/lastdir)
-
Can append below statement to ~/.bash_logout
echo `pwd` >~/.lastdir
-
(as @isaac-Zhao suggested) add the following to ~/.bash_profile
cd $(<~/.lastdir)