Directory Stack

Change directories like a pro


Posted: January 31, 2023

You may already know how to quickly navigate to your home directory with:

cd
cd ~
cd "${HOME}" # <-- Arguably not that quick :)

But did you also know that you can quickly go to the previous directory with cd -?

# change dir to /etc
$ cd /etc

# next, change dir to /var/log
$ cd /var/log

# now change back to previous dir (/etc in this case)
$ cd -
/etc

# can be used multiple times
$ cd -
/var/log

In fact, Bash can keep track of a so called “directory stack”, you can use the stack with commands such as:

These can be very useful in Bash scripts, where you want to quickly switch between multiple directories. You can read more about using these commands in this How-To Geek article.