76

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?

105

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
20

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.

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.