last-working-dir.plugin.zsh 800 B

12345678910111213141516171819202122232425
  1. #!/usr/bin/env zsh
  2. # Keeps track of the last used working directory and automatically jumps
  3. # into it for new shells.
  4. # Flag indicating if we've previously jumped to last directory.
  5. typeset -g ZSH_LAST_WORKING_DIRECTORY
  6. mkdir -p $ZSH_CACHE_DIR
  7. cache_file="$ZSH_CACHE_DIR/last-working-dir"
  8. # Updates the last directory once directory is changed.
  9. function chpwd() {
  10. # Use >| in case noclobber is set to avoid "file exists" error
  11. pwd >| "$cache_file"
  12. }
  13. # Changes directory to the last working directory.
  14. function lwd() {
  15. [[ ! -r "$cache_file" ]] || cd "`cat "$cache_file"`"
  16. }
  17. # Automatically jump to last working directory unless this isn't the first time
  18. # this plugin has been loaded.
  19. if [[ -z "$ZSH_LAST_WORKING_DIRECTORY" ]]; then
  20. lwd 2>/dev/null && ZSH_LAST_WORKING_DIRECTORY=1 || true
  21. fi