Preserving $OLDPWD across terminal sessions

John M. HigginsJune 10, 2025

Have you ever typed this command?

$ cd -

Specifying "-" as the target file will make you 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:

-bash: cd: OLDPWD not set

This error message is displayed because 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! So how do you fix this?

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.