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.

Freedom_Ben
  • 8,942
  • 7
  • 26
  • 36
  • 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 06 '18 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 – Freedom_Ben Dec 06 '18 at 18:48
  • That's obvious.. but somehow I missed the implicit "bounce around" part of your question. – tpb261 Dec 09 '18 at 08:53

3 Answers3

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.

Stephen Davison
  • 101
  • 1
  • 4
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.

Eric Carvalho
  • 53,609
  • 102
  • 137
  • 162
2

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

glenn jackman
  • 17,625
  • 2
  • 37
  • 60
  • 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 08 '13 at 20:36
  • 3
    @Freedom_Ben This can be simplified to `cd "$(dirs +1)"` – Gilles 'SO- stop being evil' Jul 10 '13 at 13:50
  • @Gilles When I try to do this, it says "bash: cd : No such file or directory" even though it clearly exists. Do you know why that is? Is cd not interpreting properly as a path? From the error message, it looks like it should work. i.e., looks correct and if I simply type out "cd ", it works. – nukeguy Sep 07 '16 at 15:37
  • 1
    @nukeguy Does `` 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)"` – Gilles 'SO- stop being evil' Sep 07 '16 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 07 '16 at 16:21