CDPATH

CDPATH is an environment variable under UNIX, which is referred every time cd command is invoked.

The working of cd

Let’s say you invoke the following command:

cd blog

The directory blog is looked in current working directory. If found, the current working directory is changed to that. If it is not found there, it is looked in every path in the CDPATH variable. Again if found, it is changed. If not then a directory not found message is displayed and cd returns 1 (Error code).

Structure of CDPATH variable

CDPATH is similar to any other PATH variable for it contains several paths separated by colons.

Example:

/home/username/:/home/username/Desktop/:/home/username/workspace/:/home/username/toolkit/

can be content of CDPATH variable.

What this means is, the above directory blog is searched in all these directories one by one. If found, navigated to it.

Multiple occurrences of a directory

Say that the directory blog is in Desktop as well as workspace . In such case, the first occurring parent will get precedence. And even before consulting the CDPATH the current working directory will get preference.

In fact, CDPATH is only referred if the directory is not found in current working directory. And when a directory is found in CDPATH, the cd command echos the complete path of directory where it has navigated to.

For example:

somedir>cd blog
blog>

will simply cd into blog directory. But if blog was not found in current working directory and instead found in /home/username/Desktop, the output will look something like this:

somedir>cd blog
/home/username/Desktop/blog
blog>

The line is for us to understand that we have been navigated somewhere far and not in the current working directory.

This is a very helpful tip for quick navigation. We don’t have to type long path names every time. Frequent paths can be added to CDPATH. The best is, cd auto completion in terminal works with CDPATH and suggests paths from all the available directories!

Updated: