Skip to content

Instantly share code, notes, and snippets.

@atelierbram
Last active October 31, 2023 16:58
Show Gist options
  • Save atelierbram/d1f0e71611d8881d5167afaef96832d9 to your computer and use it in GitHub Desktop.
Save atelierbram/d1f0e71611d8881d5167afaef96832d9 to your computer and use it in GitHub Desktop.
Create a persistent directory stack in zsh

First, make a new file with the following contents:

#!/usr/bin/env ruby

dirs = []
ARGF.each { |line| dirs.push(line) }

dirs.reverse.each { |line| puts "pushd #{line.chomp.gsub(/s/, ' ')}" }

Name the file savedirs.rb, save it somewhere in your path, and make it executable with chmod +x savedirs.rb.

Next, add these lines to your ~/.zlogout file (create it if necessary):

# Save directory stack
dirs -p | savedirs.rb > ~/.dirstack

Finally, add these lines to your ~/.zshrc file:

DIRSTACKSIZE=8
setopt autopushd pushdminus pushdsilent pushdtohome
# alias dh='dirs -v'
alias dh='dirs -v ; echo -n "\nGo to: " ; read n ; cd -$n'

Restore directory stack source ~/.dirstack

You can use dh (directory history) to show the stack:

% dh
0       /var
1       /etc
2       /Applications
3       ~/Development/Scripts

Use cd -3 to change to ~/Development/Scripts, for example. The directory stack will now be saved across shell sessions, with the added bonus that your shell will now open in the directory you were in last.

You will be prompted to choose from the list (by number). Also, you can set DIRSTACKSIZE to a larger number if you want it to remember more directories.

@devnoname120
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment