Awesome CLI tip: Quick directory navigation using $CDPATH

File this under “I wish I had known this 20 years ago!”

Most command-line veterans are already well aware of the $PATH environment variable, which is simply a list of directories that the shell will search, in order to look for the executable commands that you invoke without fully specifying the location of the command.

There’s also a similar environment variable called $CDPATH, which works in a similar fashion, except that $CDPATH contains a list of directories that you want the shell to search through whenever you use the cd (change directory) command.

So let’s say that I have a specific git repo folder that’s buried in several levels of directories in my home folder, such as ~/Documents/dev/git_repos/myproject. Instead of having to type cd ~/Documents/dev/git_repos/myproject every time you need to change to that directory, you just can add that directory to the $CDPATH. You can then simply type cd myproject from anywhere in the filesystem, and the current working directory will immediately change to that same folder!

For this example, this is what the $CDPATH variable looks like in my .zprofile (this also works in Bash):

export CDPATH=".:$HOME:/$HOME/Documents/dev/git_repos"

Each directory that I want to have access to is added to this variable, separated by colons. It’s a good idea to make the current working directory (the “.” symbol) the first directory in $CDPATH, so that it looks for that folder in whatever directory you’re currently in first (the cd command searches the folders in $CDPATH in left-to-right order). I also like adding $HOME as the second directory, so that I can quickly switch to any top level folder in my home directory.

The neat thing about $CDPATH is that not only can you quickly cd to the root of the directories you add to it, but it also allows you to change to any of the top-level subfolders within that directory. That’s why I didn’t have to explicitly add the “myprojects” directory to the $CDPATH environment variable.

If I wanted to switch to the root of the git_repos folder, I’d type…

cd git_repos

But if I wanted to switch to the “myproject” subdirectory within that git_repos folder, I can simply type…

cd myproject

And the current working directory would switch to ~/Documents/dev/git_repos/myproject

This is a great feature, but also explains why it’s very important that the CDPATH variable always starts with the current working directory (“.”), so that the cd command won’t switch to an unexpected folder in the event that you want to change to a folder with that same name in your CWD.