DEV Community

Pete Freitag
Pete Freitag

Posted on • Originally published at petefreitag.com

The difference between cd - vs cd ~-

The other day I posted one of my old (from 16 years ago) blog entries on twitter, Backtracking with Bash which shows a cool trick you can use to go to the directory you were previously in using cd ~- for example:

$ cd /var
$ cd /etc
$ cd ~-
$ pwd
/var

Ryan Guill pointed out that cd - also works, so what is the difference between cd ~- and cd -?

$ cd /var
$ cd /etc
$ cd -
/var
$ pwd
/var

So what is the difference?

The biggest difference between cd ~- and cd - is that ~- can be used in any command because it is part of the shells tilde expansion. The - shortcut can only be used with the cd command.

So for example if your directory was previously /var/log/apache2 and you want to tail the access_log file in there you can just tail ~-/access_log

$ cd /var/log/apache2
$ cd /etc
$ tail ~-/access_log
It Works...
$ tail -/access_log
tail: illegal option -- /

The second difference is that cd - will print the directory it changed to out to standard output, and cd ~- just changes directories without printing anything.

Cool trick eh?

Discussion (6)

Collapse
vinistock profile image
Vinicius Stock

You can also do git checkout - to switch to the previous branch. I use that one all the time.

Collapse
pfreitag profile image
Pete Freitag Author

Nice tip, thanks!

Collapse
aligeorgie profile image
Ali

so can you use either cd or git checkout and they will both enable you to move into the desired branch?

Collapse
vinistock profile image
Vinicius Stock

Using cd - will change to the previous directory and git checkout - or git switch - will change to the previous branch.

Collapse
moopet profile image
Ben Sinclair

TIL. That's pretty sweet-o neat-o.

Collapse
learnbyexample profile image
Sundeep

Cool, didn't know about this one. And nicely explained with examples.