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

36,073

Solution 1

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

Solution 2

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.

Solution 3

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!

Share:
36,073

Related videos on Youtube

hobodave
Author by

hobodave

Updated on September 17, 2022

Comments

  • hobodave
    hobodave over 1 year

    Sadly, I only learned about this last year by stumbling upon it randomly on the internet. I use it so infrequently that I always forget what it is by the time I need it again.

    How do you change to your previous directory?