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:
pushd
changes directory, populates the stack, and prints the stackdirs
prints a list of directories that are in the stackpopd
changes directory and removes it from the stack
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.