Angelos Orfanakos

Restore last working directory in Bash

After switching from Zsh to Bash, I missed the ability to restore the last working directory when opening a new terminal. So I came up with my own, simple implementation.

The contents of restore_last_dir.sh:

save_last_dir() {
  echo "BASH_LAST_DIR=\"$PWD\"" >~/.bash_lastdir
}

trap save_last_dir EXIT

function cd() {
  builtin cd "$@" >/dev/null
  save_last_dir
}

[[ -f ~/.bash_lastdir ]] &&
  source ~/.bash_lastdir &&
  [[ -d "$BASH_LAST_DIR" ]] &&
  cd "$BASH_LAST_DIR"

To use it, you simply have to insert the following line in your ~/.bashrc:

source ~/path/to/restore_last_dir.sh