Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How can I get the behavior of using popd without actually popping the last directory off of the stack? In other words, I want to navigate back to the last directory that I set with pushd, but I want it to stay at the top of the stack so the next popd will take me to that same directory (which would still be on the top of the stack) again.

share|improve this question
up vote 2 down vote accepted

How about: cd "$(dirs -l -p | sed -n '2{p;q}')"

share|improve this answer
Awesome, thank you! That's some bash-fu if I've ever seen it. I aliased that command to peekd (kind of C++ STL-ish and easy for me to remember), so I can just type peekd to get the behavior. alias peekd='cd "$(dirs -l -p | sed -n '\''2{p;q}'\'')"' – Freedom_Ben Jul 8 '13 at 20:36
@Freedom_Ben This can be simplified to cd "$(dirs +1)" – Gilles Jul 10 '13 at 13:50

If I understood correctly, you could pushd . just after popd so the poped directory will be placed again at the top of the stack.

share|improve this answer
Wow that is a very easy and elegant solution. Thanks! – Freedom_Ben Jul 8 '13 at 20:27

pushd with no arguments swaps the top two entries on the stack, allowing you to effectively cd back and forth between them.

Starting out in d1, execute pushd d2 adds d1 and d2 to the stack and leaves you in d2. Execute pushd again with no arguments, and you're back in d1 with d1 and d2 reversed on the stack.

share|improve this answer
Good tip, thanks! – Freedom_Ben Aug 24 '14 at 13:56

Your Answer


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.