an9wer

Faster Directory Jumps Using CDPATH

Posted:

2025-03-22

When it comes to quickly navigating between directories, there are many tools available. I used to rely on a tool called z to quickly jump between frequently used directories. However, in rare cases, it would take me to the wrong directory, which made me feel that I couldn’t fully trust the tool. Also, I like to keep my system minimal, so I avoid installing extra packages whenever possible. That leads me to a built-in shell feature - CDPATH, which is a environment variable allowing me to define a set of directories I can jump to. Using CDPATH is straightforward - I can add any directories I want, just by seperating them with colons.

For example, let's say I have two directories, "DirA" and "DirB", each containing a bunch of subdirectories that I want to navigate to quickly. Here's how I can define them in CDPATH:

$ CDPATH=/long/long/path/to/DirA:/other/long/long/path/to/DirB

If one of the subdirectories in "DirA" is "SubdirA", here's how I can jump to it:

$ cd SubdirA

As shown in the above example, I don't need to type the full path of the subdirectory (i.e., "/long/long/path/to/DirA/SubdirA"), nor do I need to worry about the directory where I currently am.

In some cases, I need to exclude certain subdirectories from CDPATH. For example, let's say "DirA" contains two subdirectories - "SubdirA" and "SubdirAA", and "DirB" contains two subdirectories - "SubdirB" and "SubdirBB". If I only want to use CDPATH to navigate to "SubdirA" and "SubdirB". I can create a seperate directory (e.g., "~/.cdpath") to collect just those, and use symbolic links to point to them:

$ mkdir ~/.cdpath
$ CDPATH=~/.cdpath
$ ln -s /long/long/path/to/DirA/SubdirA ~/.cdpath/SubdirA
$ ln -s /other/long/long/path/to/DirB/SubdirB ~/.cdpath/SubdirB

Then, navigating to them is easy:

$ cd SubdirA
$ cd SubdirB

Thanks for reading :)