Quick and easy directory navigation using CDPATH

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/maheshrijal/Code directory. But, every time I want to go into one of the sub directories inside /home/maheshrijal/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/maheshrijal/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/maheshrijal/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.

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

However, once the CDPATH variable is properly configured:

maheshrijal@workstation:~$ pwd

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


I’m able to CD into dotfiles directory directly without having to type 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 (😃 separated directories just like the PATH variable.

$ export CDPATH=/home/maheshrijal/Code:/home/maheshrijal/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.