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

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

  • This answer just begs for some examples! – Johan Jun 26 '13 at 9:31
  • @Johan better now? Thanks for prodding me to expand! – tripleee Jun 26 '13 at 10:49
  • Good but what about a $DIRSTACK[2] example ? – Johan Jun 26 '13 at 11:24
  • Probably good enough to have in your cimment (-: – tripleee Jun 26 '13 at 12:06
2

Yes, in bash:

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

or even simpler:

cp ~2 ~/code/bar/view/static/css/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.