skip to content
Hi! 👋 Mahesh Rijal

Quick and easy directory navigation using CDPATH

/ 2 min read

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

Terminal window
mahesh@workstation:~$ cd dotfiles
bash: cd: dotfiles: No such file or directory

However, once the CDPATH variable is exported, I’m able to cd into dotfiles directory directly without having to type the complete path.

Terminal window
mahesh@workstation:~$ export CDPATH=/home/mahesh/code/
mahesh@workstation:~$ cd dotfiles
/home/mahesh/code/dotfiles

Additionally, all directories under /home/mahesh/code/ will also show up as suggestions in bash.

The CDPATH variable can also contain multiple colon : separated directories just like the PATH variable.

Terminal window
$ export CDPATH=/home/mahesh/code:/home/mahesh/Documents

Something to keep in mind is that, the order in which you define the directories with CDPATH determines where you end up. So there could be issues if subfolders across exported CDPATH’s have the same name.

While CDPATH is easy effective but it does run into issues. While changing directories, it can jump into unexpected directories and it writes text to the standard output, which is bad for shell scripts.

I have my CDPATH exported in ~/.bashrc so that the the change is applied only in interactive shells.