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.
See this zsh plugin as an alternative: https://github.com/ohmyzsh/ohmyzsh/tree/master/plugins/dirpersist