Preserving $OLDPWD across terminal sessions
Running CD with "-" as the target file will change your current working directory to be whatever the previous working directory was. If you use it after opening a fresh terminal session you'll see this message:
$ cd -
-bash: cd: OLDPWD not set
This error appears when the CD command hasn't been used to navigate to a different directory yet. So there is no $OLDPWD because there is no historical current working directory!
One workaround is to make the variable global so that all terminal sessions have access to it. This can be accomplished with the following snippet of shell code:
export OLDPWD=$(test -f ~/.oldpwd && cat ~/.oldpwd);
function __oldpwdcd {
if test -d "$1"; then
\cd $@;
echo $( realpath "$1" ) > $HOME/.oldpwd;
elif [ "-" = "$1" ]; then
\cd $OLDPWD;
else
\cd $@;
fi
}
alias cd='__oldpwdcd';
Now when you open your shell, you can type "CD -" and it will move you to whatever directory you CD'd to in a previous terminal session.
It's not ground breaking but it is convenient when you want to make a new tab in your terminal in the same directory you were in previously.