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 Answers
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.
If I understood correctly, you could pushd .
just after popd
so the pop
ed directory will be placed again at the top of the stack.
How about: cd "$(dirs -l -p | sed -n '2{p;q}')"
-
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 typepeekd
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.– nukeguySep 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 becd "(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.– nukeguySep 7, 2016 at 16:21
cd -
works, but only if you don'tcd
anywhere else until you are ready topopd
. I usually bounce around to a few places before I'm ready to return