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 do that, then another subtle point noted in the bash Reference comes into play:

“If a nonempty directory name from $CDPATH is used, or if '-' is the first argument, and the directory change is successful, the absolute pathname of the new working directory is written to the standard output.”

In other words, pretty much every time you use cd it will echo the new path to STDOUT, which is not the standard behavior.

Common directories to include in $CDPATH are:

.

The current directory (see the warning above)

~/

Your home directory

..

The parent directory

../..

The grandparent directory

~/.dirlinks

A hidden directory containing nothing but symbolic links to other commonly used directories

The above suggestions result in this:

export CDPATH='.:~/:..:../..:~/.dirlinks'
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.111.208