Secret features in your Unix shell: CDPATH

Create a shortcut with CDPATH

Have you ever noticed that when you type a single letter in your browser’s address bar, it will automagically suggest the website you want to visit?

In essence, websites are just visually pleasing representations of data. Old-fashioned programmers don’t use websites for reading, writing and test-driving their code, but work with raw files and directories.

Much like a browser’s address bar, computer programs have the notion of a “current directory”. To navigate the directory hierarchy, many programs – most prominently command-line shells – offer a cd command (“change directory”).

What is CDPATH?

When using cd frequently, it can become a chore to type cd /full/path/to/the/target/directory every time. There are multiple remedies, but the one we’ll be taking a look at today is CDPATH, which is a variable that holds a list of directories. When you pass a relative path to cd, then the directories in $CDPATH will be used as base directories.

The CDPATH variable is fairly old and is supported by all major Unix shells. For example, here are the corresponding documentation entries for bash and fish.

Here’s how to try it. First, let’s create a directory hierarchy.

% mkdir places-to-be
% mkdir places-to-be/hogwarts
% mkdir places-to-be/narnia
% mkdir places-to-be/the-shire
% tree places-to-be
places-to-be/
├── hogwarts
├── narnia
└── the-shire

Phew 😅. With that out of the way, here’s where the magic happens.

Simply add the places-to-be directory to your $CDPATH:

% CDPATH=$CDPATH:$PWD/places-to-be

From now on, you can always go back to your favorite directory with cd narnia, from wherever you are:

% cd ..
% cd ..
% pwd
/Users/
% cd narnia
~/places-to-be/narnia
% pwd
/Users/johannes/places-to-be/narnia

Pre-tty cool, right?

But there’s more: if you are using fish, you can also get automatic suggestions for your cd commands, just like you would in your web browser. All you need to do is to type cd n, then fish suggests cd narnia, since it’s likely the only valid choice. Afterwards, you just type (or Control+F) to accept the suggestion.

What do you think? Did you like this quick look at the CDPATH feature? If you want to see more content from Symflower, don’t forget to subscribe to our newsletter, and follow us on Twitter, Facebook, and LinkedIn as well. See you next time!

Technical | 2021-11-26