How to cd to a directory using partial naming

Posted on Thu 17 November 2011 in linux

Annoyed sometimes because directories you want to change to have very long names or repeating prefix or just plain silly cumbersome naming?

If the "cdspell" from the shopt builtin is not enough for you, and you are annoyed by the fact that -exec cannot call a builtin such as cd as in:

$ find -name '*part_name*' -exec cd {} \;

then what you want is to simply add this small yet effective simple function to your .bashrc and enjoy the ability to change into a directory only typing its name partially.

Add the following to your .bashrc (if you're using Bash):

function cdd() { cd `find $PWD/. -maxdepth 1 -name "*$1*" -type d -print0 -quit`; }

This is how my .bashrc looks like after adding the line above:

.bashrc

Out of all the options to find, the most important is -maxdepth, which is going to make the find command exponentially faster and is going to render our cdd command practically as fast as cd. Check out the man page for find for further details.

This is the resulting output of using the function cdd from the command line:

cdd examples

This of course has its limitations, such as cding into the first result returned by find or not being able to process $ cdd ../[part_name] (try it to see what happens).

I encourage you to improve on the function above and make it more flexible and useful. But for the time being, it's not a bad quick hack at all, huh?