Bash – way to cd back multiple times in bash?


I often use cd - to go back to where I was. How can I do this multiple times in bash? Or would zsh or some other tool support this?

Best Answer

  • 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.