Setting Your $CDPATH

Problem

You want to make it easier to switch between several directories in various locations.

Solution

Set your $CDPATH appropriately. Your commonly used directories will likely be unique, so for a contrived example, suppose you spend a lot of time working with init’s rc directories:

/home/jp$ cd rc3.d
bash: cd: rc3.d: No such file or directory

/home/jp$ export CDPATH='.:/etc'

/home/jp$ cd rc3.d
/etc/rc3.d

/etc/rc3.d$ cd rc5.d
/etc/rc5.d

/etc/rc5.d$

/etc/rc5.d$ cd games
bash: cd: games: No such file or directory

/etc/rc5.d$ export CDPATH='.:/etc:/usr'

/etc/rc5.d$ cd games
/usr/games

/usr/games$

Discussion

According to the bash Reference, $CDPATH is “a colon-separated list of directories used as a search path for the cd built-in command.” Think of it as $PATH for cd. It’s a little subtle, but can be very handy.

If the argument to cd begins with a slash, $CDPATH will not be used. If $CDPATH is used, the absolute pathname to the new directory is printed to STDOUT, as in the example above.

Warning

Watch out when running bash in POSIX mode (e.g., as /bin/sh or with --posix). As the bash Reference notes:

“If $CDPATH is set, the cd built-in will not implicitly append the current directory to it. This means that cd will fail if no valid directory name can be constructed from any of the entries in $CDPATH, even if a directory with the same name as the name given as an argument to cd exists in the current directory.”

To avoid this, explicitly include . in $CDPATH. However, if you ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.