Go Back to the Previous Directory via Command Line
It’s easy to accidentally change directories to something you weren’t intending to (say, accidentally hitting cd and returning home, thus losing your place in a complicated directory structure seep in the file system somewhere), but thankfully there’s a command that will immediately take you back to the previous directory, regardless of what it was. The jump-back to prior directory command is a simple variation on ‘cd’ followed by a single dash (the minus symbol), the syntax looks like so:
It’s that simple, cd – will take you to the directory you were in prior to the PWD (Present Working Directory), and it will print out the prior directory as well so you will know you’re in the right place. You can try it out yourself by opening a Terminal window, navigating somewhere within the file system, then immediately switching directories to another location. Now just type cd – to switch back to the prior location, and cd – again to switch back to the original location.
You can think of cd – as kind of like a back button for the command line, it will instantly jump back to the previously current directory.
This is not only helpful if you lost your place somewhere accidentally while at the command line, but it’s also very useful if you are working in two different directories and you want to quickly go back and forth between them, just keep typing cd – and you will keep switching between the two directories!
This command line tip works in every variant of Unix I’ve used, so whether you’re in the Mac OS X command line (which is based on BSD) or Linux, you should be covered. It also works regardless of how deep into a directory structure you are or were, so you can seamlessly toggle your place in the file system with cd – try it out yourself, you’ll be thrilled with the result.
This is just one of a handful of essential change directory (AKA cd) command tricks that Terminal users should know, don’t miss these other essential ‘cd’ command tips too.