Remember last used directory across sessions in bash

Revision history
Tags: bash

Stumbled around to replace a function I used to have in zsh which remember my last used directory. I recently went back to using bash in yet another step towards a more simpler stack (and life).

Anyway, I ended up appending the below to my .bashrc:

# Rembember last used directory
LAST_DIR_FILE="/tmp/.lastdir"
function cd() {
  builtin cd "$@"
  pwd > $LAST_DIR_FILE
}
if [ -f "$LAST_DIR_FILE" ]; then
  cd `< $LAST_DIR_FILE` 
fi

The builtin command prevents endless recursion when calling cd by calling on the actual builtin function

References

If you have any comments or feedback, please send me an e-mail. (stig at stigok dotcom).

Did you find any typos, incorrect information, or have something to add? Then please propose a change to this post.

Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.