Keeping a cd history in the Bash shell

Often I find myself wanting to cd back to a directory -- but never the exact previous one I was already in (i.e., cd -)!  It is usually the directory I was in just a few of cd's ago.

I was considering writing a bash shell function that more or less aliased cd to pushd with some cleanup to keep the stack only about 10 levels deep. But I found someone else (Petar Marinov) beat me to this back in 2004:

Add this code to your login shell and the last 10 directories you were in will be saved in a stack. Listing the previous directories is as easy as 'cd --' and going to a previous one is simple: 'cd -#' where # is the number in the history:

[centos6:/tmp/ssh-ZhqNv10269]$ cd /tmp
[centos6:/tmp]$ cd cow
[centos6:/tmp/cow]$ cd fox
[centos6:/tmp/cow/fox]$ cd fish
[centos6:/tmp/cow/fox/fish]$ cd elephant/
[centos6:/tmp/cow/fox/fish/elephant]$ cd rhino/
[centos6:/tmp/cow/fox/fish/elephant/rhino]$ cd zebra/
[centos6:/tmp/cow/fox/fish/elephant/rhino/zebra]$ cd --
 0  /tmp/cow/fox/fish/elephant/rhino/zebra
 1  /tmp/cow/fox/fish/elephant/rhino
 2  /tmp/cow/fox/fish/elephant
 3  /tmp/cow/fox/fish
 4  /tmp/cow/fox
 5  /tmp/cow
 6  /tmp
 7  /tmp/ssh-ZhqNv10269
[centos6:/tmp/cow/fox/fish/elephant/rhino/zebra]$ cd -3
[centos6:/tmp/cow/fox/fish]$ cd -7
[centos6:/tmp/ssh-ZhqNv10269]$ cd -1

If you incorporate this code, know that the conditional around the bind is broken, so just remove the conditional if you want the bind.


Popular posts from this blog

Repairing a Moenstone Composite Granite Sink

Our Leopard Gecko Bioactive Build for Banana

When to ask for help when stuck on a technical problem