Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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

share|improve this question

2 Answers 2

up vote 3 down vote accepted

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

share|improve this answer
    
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

Yes, in bash:

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

or even simpler:

cp ~2 ~/code/bar/view/static/css/
share|improve this answer
    
This refers to argument 1 of the previous command, not to the directory stack, I believe? And thus where it says dirs it would appear that the actual command is history. –  tripleee Jun 26 '13 at 10:51
    
Quite so - corrected now thanks –  suspectus Jun 26 '13 at 11:06

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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