Create a persistent directory stack in zsh

Aug 12, '05 09:26:00AM

Contributed by: Anonymous

The directory stack keeps track of the various directories you've visited in a given shell session. Here is a way to make the stack persistent using zsh. The aim is to make it easier to switch between frequently visited directories. The basic idea for this was taken from a 1991 Usenet posting by Uri Guttman. Other bits come from Paul Falstad's Z Shell Guide.

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'

# 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.

Comments (16)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20050806202859392