What is the bash shortcut to change to the previous directory?

The shortcut is -

Try cd -

If you want to use this in your prompt, you have to refer to it with ~-.

See the example:

[echox@kaffeesatz ~]$ cd /tmp
[echox@kaffeesatz tmp]$ ls
cron.iddS32  serverauth.CfIgeXuvka
[echox@kaffeesatz tmp]$ cd -
/home/echox
[echox@kaffeesatz ~]$ ls ~-
cron.iddS32  serverauth.CfIgeXuvka

You might also want to look at pushd and popd, which create a stack of directories to remember where you were.

To use, pushd <directory> changes to <directory> and saves the previous directory. To change back to this saved directory, use popd.


As per the answer by @echox, you can indeed use cd - as the man page for bash explains:

When a is used as the operand, this shall be equivalent to the command:

                cd "$OLDPWD" && pwd

which changes to the previous working directory and then writes its name.

Note the changed-to directory is output by the inherent pwd in cd -. You may not want that output in a script. That's where the alternative becomes useful - just do

cd "$OLDPWD"

and you're done!