last-working-dir.plugin.zsh 887 B

123456789101112131415161718192021222324252627
  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. typeset -ga chpwd_functions
  10. chpwd_functions+='chpwd_last_working_dir'
  11. function chpwd_last_working_dir() {
  12. # Use >| in case noclobber is set to avoid "file exists" error
  13. pwd >| "$cache_file"
  14. }
  15. # Changes directory to the last working directory.
  16. function lwd() {
  17. [[ ! -r "$cache_file" ]] || cd "`cat "$cache_file"`"
  18. }
  19. # Automatically jump to last working directory unless this isn't the first time
  20. # this plugin has been loaded.
  21. if [[ -z "$ZSH_LAST_WORKING_DIRECTORY" ]]; then
  22. lwd 2>/dev/null && ZSH_LAST_WORKING_DIRECTORY=1 || true
  23. fi