Is there a way to cd back multiple times in bash?

In zsh, there's an auto_pushd option. This option makes cd behave like pushd. Then you can just use popd to go back to previous directories.

~ $ setopt auto_pushd
~ $ cd /
/ $ cd /var
/var $ cd /usr
/usr $ dirs
/usr /var / ~
/usr $ popd
/var $ popd
/ $ popd
~ $

In Bash, you can alias cd to pushd.

alias cd=pushd

The one downside of this is that you will lose cd's three flags. From the cd help entry:

-L force symbolic links to be followed
-P use the physical directory structure without following symbolic links
-e if the -P option is supplied, and the current working directory cannot be determined successfully, exit with a non-zero status

If you ever have to use the actual cd builtin instead of the alias, you can use one of these:

  • 'cd' - Quoting the command makes the shell not resolve the alias and use the normal cd.
  • \cd - Backslashes quote characters. If you quote one character of a word, the shell treats the whole word as quoted.
  • builtin cd - This directly tells the shell to use the builtin instead of the alias.

Here's a quick and dirty way to conveniently bookmark directories and jump back to them:

$ a() { alias $1="cd $PWD"; }

Go somewhere and type:

$ a 1

You now have a command called 1 which does cd the directory that is current at this time. Later just type:

$ 1

And presto, back to that directory. I find this very useful.


bash

I found a script, available here, that solved this issue for me. With this you can type cd -- to see the last 10 directories that you've used. It'll look something like this:

0  ~/Documents/onedir
1  ~/Music/anotherdir
2  ~/Music/thirddir
3  ~/etc/etc

To go to ~/Music/thirddir just type cd -2

zsh

oh-my-zsh provides some really nice functionality for this (at least I think it's oh-my-zsh that sets this).

Basically, d is aliased to dirs -v | head -10

dirs is a zsh built-in command and shows the last directories you've been to.

Also, 1 is aliased to cd -1 and so on for all numbers to 9.

In practice, it works like this:

$ pwd
/home/me/Documents/gems/java_regex/lib

$ d
0       ~/Documents/gems/java_regex/lib
1       ~/Documents/gems/java_regex
2       ~/Documents/gems
3       ~/Documents
4       ~

$ 2
~/Documents/gems

$ pwd
/home/me/Documents/gems