9

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.

3
  • Will not "cd -" work? If I understand, the sequence is: "pushd d1; pushd d2; pushd d3;" and now to go back to d2, right?
    – tpb261
    Dec 6, 2018 at 11:51
  • cd - works, but only if you don't cd anywhere else until you are ready to popd. I usually bounce around to a few places before I'm ready to return Dec 6, 2018 at 18:48
  • That's obvious.. but somehow I missed the implicit "bounce around" part of your question.
    – tpb261
    Dec 9, 2018 at 8:53

3 Answers 3

10

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.

0
6

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

1
  • Wow that is a very easy and elegant solution. Thanks! Jul 8, 2013 at 20:27
2

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

5
  • 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}'\'')"' Jul 8, 2013 at 20:36
  • 3
    @Freedom_Ben This can be simplified to cd "$(dirs +1)" Jul 10, 2013 at 13:50
  • @Gilles When I try to do this, it says "bash: cd <my directory>: No such file or directory" even though it clearly exists. Do you know why that is? Is cd not interpreting <my directory> properly as a path? From the error message, it looks like it should work. i.e., <my directory> looks correct and if I simply type out "cd <my directory>", it works.
    – nukeguy
    Sep 7, 2016 at 15:37
  • 1
    @nukeguy Does <my directory> start with a tilde? My comment above was missing the -l option to list the full directory rather than using the ~ abbreviation. It should be cd "(dirs -l +1)" Sep 7, 2016 at 16:11
  • @Gilles Yes! That's exactly what I was looking for, thanks! Perhaps you should post your comment as a separate solution -- in my opinion, it's the most general and useful option on this thread.
    – nukeguy
    Sep 7, 2016 at 16:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .