Ubuntu – Keep $OLDPWD between Shell Sessions


Often, I'm leaving the terminal and the next day run it again. Then I want to be able to quickly go back to the last working directory.

I would like to do this using cd - as usual. But $OLDPWD is not kept between terminal sessions.

So I added an alias for exit to write pwd to a file and read it on the next start.

alias exit='pwd > ~/.lwd && exit;'
test -f ~/.lwd && export OLDPWD=`head -1 ~/.lwd`

That works perfectly for exit.

How can I create the same alias (or make a trap) for Ctrl+D ?

Best Answer

Use trap to add a handler for EXIT:

trap 'pwd > ~/.lwd' EXIT

This should handle both the exit command and CtrlD. The rest, you can do as with the alias.