Unix/Linux trick: ‘cd’ back to the previous directory

You know when you’re in a very “deep” directory, such as
/usr/local/src/this/that/thatother, and you type “cd” and press enter by mistake(1) and go back to your home directory, and would love to go back to where you were before, without having to type all the path again (or copy and paste it, or do a CTRL-R back search)?

Just type “cd -” (that’s a single dash, or “minus” sign). Believe it or not, I didn’t know that until today, and I’ve used Linux since 1994 or so. Slightly embarrassing, I know. :)

If you enter the command a second time, you will return to where you were before typing the first “cd -“. In other words, the command can be used to toggle between the previous directory and the current one.

It’s also not just a bash thing; I’ve tried it on FreeBSD’s sh and OpenBSD’s default ksh, and it works there as well.

(Found here, after someone asked me and I didn’t know the answer.)

P.S: – Welcome to the first technical post on Winterdrake. (Hey, it’s geeky stuff, too!)

  1. happens a lot when you think there’s only one directory where you are, so you type "cd <tab><enter>“, but there was in fact more than one, and the tab key didn’t add anything []

This entry was posted in Computers, Linux, Unix and tagged , . Bookmark the permalink.

9 Responses to Unix/Linux trick: ‘cd’ back to the previous directory

  1. Alex says:

    I do this all the time, and likewise have used linux for a number of years but I never thought it this was possible because I had never asked my self. I would just do it the long way and go back into my deep directory. Thank you.

  2. Mahesh says:

    cool! Thanks a lot.

  3. PBJ says:

    Works from git shell on Windows 7

  4. Frode says:

    You also have pushd and popd to push and pop the directory you’re in on the stack, it gives you even more flexibility

  5. Martin Thoma says:

    Very nice! Thank you very much!

  6. maximmaI says:

    Very helpful, thank you!

    I didn’t know until today.

  7. karatedog says:

    It is not just the previous dir and the other.

    Use ‘pushd’ with a directory argument. It will push the current dir and the argument to a ‘stack’:
    /home/user/work > pushd /home/user/work/this/that/whatever
    ~/work ~/work/this/that/whatever

    Now you can go back and forth between those 2 using ‘cd -’.

Leave a Reply