Sunday, November 4, 2012

cd is fancier than you think!

I was doing something-or-other today, when I had the urge to run "help cd".  What I found changed my life.  I will never cd the same way again.  It was so life-changing I'm taking a short break from my PLDI paper, which is due in about a week.

Apparently, there's this environment variable $CDPATH which has a list of places that cd searches for the name of the folder you specified.  For example, if you have folders like

cs242
cs300
cs1337

inside your ~/school folder, and you set CDPATH=~/school, then typing "cd cs242" will take you to ~/school/cs242, no matter what your current working directory is.

But now, I have this problem: what if there are some folders in ~ that I visit often, and others that I don't want to accidentally go to (or have short names, like ~/tmp).  Symbolic links to the rescue!

Create a folder like ~/.cddir.  Inside ~/.cddir you can create symbolic links to any folder you would like to go to.  Then add ~/.cddir to your path, and you're set!

There's one more bit of awkwardness.  If you have a symbolic link like

~/.cddir/school -> ~/school

and then you do "cd school", you'll end up in ~/.cddir/school, which isn't what you really want, because if you do "cd ..", you would prefer to be in ~, rather than ~/.cddir.  "help cd" comes back to the rescue and advises to use "cd -P" instead.  This fixes the issue.  The easy thing to do is make this an alias in your .bashrc.

To recap: go into your .bashrc and add the following:

alias cd='cd -P'
export CDPATH='~/.cddir'

Then:

cd ~
mkdir .cddir
cd .cddir

and add symbolic links like

ln -s ~/school school.

Then you would be able to use 'cd school' to get to your school folder from any working directory!