Is it possible to save the last working directory when you do an "exit" in bash. So, the next time you login, it will be at the directory you were at when you last logged out.
Save the last working directory in ~./.bash_logout into a hidden file:
pwd > ~/.lastdirectory
Read this file in ~/.bashrc with
[ -s ~/.lastdirectory ] && cd `cat ~/.lastdirectory`
Put this in your ~/.bashrc
(probably at the end):
cd "$(<~/.storepwd)"
Then you have a choice of the following:
Either put this in ~/.bash_logout
(will not remember directory for interactive non-login shells):
printf %s "$PWD" > ~/.storepwd
Or use a trap
on EXIT
, put this in your ~/.bashrc
(traps can be overwritten easily/accidently):
trap 'printf %s "$PWD" > ~/.storepwd' EXIT
Or use PROMPT_COMMAND
, put this your ~/.bashrc
(probably the most reliable way):
PROMPT_COMMAND+='; printf %s "$PWD" > ~/.storepwd'
Also make sure that your ~/.profile
or ~/.bash_profile
sources your ~/.bashrc
, otherwise the path won't be restored when login shells start.
See http://mywiki.wooledge.org/DotFiles for information on how you should use your dotfiles.
You also need to be careful with this entire concept. If, for example, you manage to get your code run when you don't expect, it can confuse any number of things.
For example, if you were to run a shell script that changed the current working directory, and then, during exit, managed to save its CWD, you may end up, in the next shell that starts up, in a directory you don't expect.
Another popular one, at least for me at $work, is when a script is run when root su's to your user to run a script, all automatically (i.e., programmatically). If you're doing this CWD trick for your own user, that's fine, but it can majorly screw up with system tools that expect that "su - youruser -c ls" returns the files in your home directory. (Ok, calling "ls" as your user is a dumb idea, but there are things where your user may have a better environment for running something than root does - e.g., on NFS mounts that have root squashed.)
So, the key here is to tell if you're in an interactive shell or not, and, if not, don't restore or save your CWD. IIRC, $- has an 'i' for interactive shells. Use it for setting the trap and for restoring the CWD.
Personally, I just set an alias:
alias go='. go.sh'
and then go.sh simply checks its parameter for which directory I want to go to. e.g., "go myproj" will cd ~/svn/myproj, and "go bigdisk" will cd /mnt/bigdisk. And, for more complex cases, it can take more parameters, e.g., "go myproj lib" would just "cd ~/svn/myproj/myproj/lib" or whatever. No automatic saving, but none of the side effects, either.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With