6

I use pushd to work with multiple directories in bash and zsh. I've aliased dirs to dirs -v so that I get an ordered list when I want to see what's on the directory stack:

chb$ dirs
0  /Volumes/banister/grosste_daever_gh/2013-03-27/reader
1  /tmp/20130618202713/Library/Internet Plug-Ins
2  ~/code/foo/view/static/css
3  ~/Downloads

Is there a way (either in bash or zsh) that I can refer to one of the directories listed on the command line using an alias for its position on the stack? For example, instead of typing:

chb$ cp ~/code/foo/view/static/css/baz.css ~/code/bar/view/static/css/

I'd type:

chb$ cp <2>baz.css ~/code/bar/view/static/css/

...or something like that, maybe using a dollar sign and a variable name instead of <n>.

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
chb
  • 584
  • 7
  • 17

2 Answers2

11

Bash exposes the directory stack in the DIRSTACK variable. You can also use the command dirs +2 to refer to the second entry on the stack.

More conveniently, ~1 through ~9 refer to the nine topmost entries on the stack. So your example would translate to

chb$ cp ~2/baz.css ~/code/bar/view/static/css/

Zsh has the same ~n facility, and the stack is exposed through an array called dirstack. Bash's dirs +2 is zsh's print -r ~2 or print -r $dirstack[2].

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
tripleee
  • 7,506
  • 2
  • 32
  • 42
2

Yes, in bash:

cp $(dirs +2) ~/code/bar/view/static/css/

or even simpler:

cp ~2 ~/code/bar/view/static/css/
suspectus
  • 5,890
  • 4
  • 20
  • 26