return to previous directory (quickly) in bash (or zsh)

2020-02-10

 | 

~1 min read

 | 

153 words

If I can quickly change directories (cd) to anywhere in my computer’s file system, how can I go back if I mistakenly navigate away from somewhere I was working?

Turns out that Bash (and Zsh) allow a quick return by using $ cd -.

According to this response on StackOverflow, this works within Bash by calling cd $OLDPWD.

This means that in Bash you can manually affect the results, however Zsh does not work that way:

$ printenv | grep OLD
OLDPWD=/Users/stephen/_coding/personal/onething
$ goHome
$ printenv | grep OLD
OLDPWD=/Users/stephen/_coding/personal/blog
$ cd -
~/_coding/personal/blog
$ printenv | grep OLD
OLDPWD=/Users/stephen
$ export OLDPWD=/Users/stephen/_coding/personal/blog
$ printenv | grep OLD
OLDPWD=/Users/stephen/_coding/personal/blog
$ cd -
~
$ cd -
~/_coding/personal/blog

Oh well, so I can’t overwrite. I can still quickly navigate back to the directory I was in if I mistakenly navigate away, which is really all I wanted in the first place.



Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!