Imagine you are working in your shell, you could be in any directory anywhere, but you want to go to ~/Projects/MyProject. You’re probably used to typing something like this:

cd ~/Proj[tab]/MyPro[tab]

Wouldn’t it be nice if you could end up in the exact folder you want with just:

cd MyProject

The CDPATH environment variable

Much like the PATH environment variable defines a search order for the executable you want, CDPATH defines the order for directories to search to when you use cd. Also like PATH, directories are separated with a :. Unlike PATH, where you want to avoid letting an executable in the current directory be “default”, you will probably want to list . (the current directory) first in your CDPATH.

Modifying your shell environment

Edit your ~/.bash_profile, ~/.zshrc, or applicable “environment script”. Add the following line using whatever folders you want to search:

# search current directory, home directory, and projects folder
export CDPATH=".:~:~/Projects"

After changing your environment startup script, you can source ~/.bash_profile to load the changes into your current shell environment.

Enabling Tab Completion in bash

If you are a zsh user, tab completion inside of folders in your CDPATH should already work. If you have an older version of bash and it isn’t working, you will need to download and install bash-completion. You can install it via your favorite package manager; apt, brew, macports, rpm etc all seem to have a package for it. You might be required to edit your ~/.bash_profile again to make it work, but it’s worth it.

Why didn’t I know this?!

I’ve been using POSIX shells for over 20 years now, and it always surprises me when I learn about a feature I’ve been missing out on for all of them. Today’s revelation came from fellow Bocouper Tim Branyen who remarked in an IRC channel that his mind had been blown. Mine was too, so I wanted to share this quick tip, but now I’m going to cd MyPro[tab] and get back to work. I hope you’ll find traversing back to work in your shell easier too.

Comments