You know about the PATH environment variable. Did you know about CDPATH? If you’ve been typing long cd commands like me, this post is for you.
I came across this gem while reading Daniel Barrett’s Efficient Linux at the Command Line. It instructs the cd command to search for the directory you specify in locations other than your current directory.
A cd search path works like your command search path $PATH. However, instead of finding commands, it finds the subdirectories. You can configure it with the shell variable CDPATH, and it has the same format as the PATH variable: a list of directories separated by colons.
Set this variable in your ~/.zshconfig or ~/.bashrc file to include the directories you visit most frequently.
export CDPATH=$HOME:$HOME/software:$HOME/software/ruby:$HOME/software/rails:$HOME/software/youtube
Now, whenever you want to cd into a directory, the shell will look through all the above places in addition to the current directory.
What’s more, the search is lightning fast. It looks only in parent directories that you specify and nothing else.
For example, let’s say you have a $HOME/software/blog directory and you’ve configured the CDPATH to include the $HOME/software directory.
Now, if you type cd blog from anywhere in the filesystem, the cd command will take you to the $HOME/software/blog directory, unless it finds another blog directory in another pre-configured path.
In the above example, cd will check the existence of the following directories in order, until it finds one or it fails.
- in the current directory
$HOME/software/blog$HOME/software/ruby/blog$HOME/software/rails/blog$HOME/software/youtube/blog
Trust me, this is pretty freaking cool. It has changed the way I use the shell.
P.S. Don't overdo it. If you put too many directories with common names into CDPATH and export it, it might break your scripts.
That's a wrap. I hope you found this article helpful and you learned something new.
As always, if you have any questions or feedback, didn't understand something, or found a mistake, please leave a comment below or send me an email. I reply to all emails I get from developers, and I look forward to hearing from you.
If you'd like to receive future articles directly in your email, please subscribe to my blog. If you're already a subscriber, thank you.