Angelos Orfanakos

Restore last working directory in Bash

Update (25 Aug 2026): Simplified implementation by using PROMPT_COMMAND, supported from Bash 5.x. This avoids overriding cd which can conflict with software like mise.

After switching from Zsh to Bash, I missed the ability to restore the last working directory when opening a new terminal. The following script does exactly that:

save_last_dir() {
  printf 'BASH_LAST_DIR=%q\n' "$PWD" > ~/.bash_lastdir
}

PROMPT_COMMAND+=(save_last_dir)

if [[ -f ~/.bash_lastdir ]]; then
  source ~/.bash_lastdir
  [[ -d "$BASH_LAST_DIR" ]] && builtin cd "$BASH_LAST_DIR"
fi

To use it, you simply have to source it in your ~/.bashrc.