1 min read

Quick & easy Directory Navigation with CDPATH

Using CDPATH to traverse through multiple directories in Linux efficiently.
Quick & easy Directory Navigation with CDPATH
Photo by Gabriel Heinzer / Unsplash

Traversing through multiple directories in Linux often takes time and can be inefficient when multiple sub directories are involved.

To easily move to directories in Linux, we can use the CDPATH variable.

I store all my code in the /home/maheshrjl/Code directory. But, every time I want to go into one of the sub directories inside /home/maheshrjl/Code, I have to CD into Code and then switch to the sub directory I am interested in.

However, if I set the CDPATH variable to /home/maheshrjl/Code I can directly jump to any of the sub directories under Code without having to traverse the full path. This can be a lifesaver when the directories are nested deep inside.

Syntax for CDPATH: export CDPATH=/home/maheshrjl/Code/

Let's see how this works practically. Initially, if I attempted to change into the dotfiles directory without CDPATH, I'd encounter an error due to the incomplete path.

maheshrjl@workstation:~$ cd dotfiles
bash: cd: dotfiles: No such file or directory

However, once the CDPATH variable is properly configured:

maheshrjl@workstation:~$ pwd

maheshrjl@workstation:~$ export CDPATH=/home/maheshrjl/Code/
maheshrjl@workstation:~$ cd dotfiles


I'm able to CD into dotfiles effortlessly. I dont have to type in the complete path.

This also extends beyond navigation. Now the directories under code will also show up as suggestions in bash.

The CDPATH variable can also contain multiple colon (:) seperated directories just like the PATH variable.

$ export CDPATH=/home/maheshrjl/Code:/home/maheshrjl/Documents
The order in which you define the directories with CDPATH determines where you end up.

CDPATH is easy & effective. But, when configured cd can jump into unexpected directories, and it writes text to the standard output, which means your shell scripts will run into error. Therefore, it is always best to implement CDPATH through ~/.bashrc so that the the change happens only in interactive shells, with no impact to non-interactive scripts.