DEV Community

Christophe Colombier
Christophe Colombier

Posted on

Tips: The power of "cd -" command

I'm often posting advanced tips, today I will talk about something very simple, but that I noticed even experienced terminal users are not aware of: the cd - command.

Quick intro about cd

The cd command, short for "change directory" is used in both Windows Command Prompt and Linux terminals to navigate through the file system.

The following command will
bring you to a folder /var/log

~$ cd /var/log
Enter fullscreen mode Exit fullscreen mode

This is basic, OK.

Navigation

Let's go further.

~$ cd src/foo/bar
src/foo/bar$ #do something, but you have to move to another folder
src/foo/bar$ cd /var/log
/var/log$ # do something, but you have to move back to src/foo/bar
/var/log$ cd ~/src/foo/bar
src/foo/bar: $ # do something, but you have to move to log folder
src/foo/bar$ cd /var/log
/var/log$ # whatever
Enter fullscreen mode Exit fullscreen mode

OK these are basic moves.

You all know cd .., cd ~, or cd, but do you know about cd - ?

cd - command

cd - will bring you back to previous folder.

Let's try the same navigation example

~$ cd src/foo/bar
src/foo/bar$ #do something, but you have to move to another folder
src/foo/bar$ cd /var/log
/var/log$ #do something, but you have to move back to src/foo/bar, we could use cd ~/src/foo/bar, but let's try cd -
/var/log$ cd -
src/foo/bar$ #do something, but you have to move to log folder, cd - will bring you back to 
src/foo/bar$ cd -
/var/log$ # whatever
Enter fullscreen mode Exit fullscreen mode

This something I'm using multiple times a day

Top comments (1)

Collapse
 
moopet profile image
Ben Sinclair

To be clear, it acts more like a toggle between the current and previous directories, so you can't keep going back farther and farther - you'd need to use pushd and popd for that but I don't think I've ever met anyone who bothers! cd - does enough for most people.

People have taken this idea and run with it in their own apps, though - for example, in git you can use git checkout - to check out the last branch or commit you were on. I think this is a great idea and have included it as a convention whenever I've written an appropriate script.