Some people make a shell alias (Section 29.2) for directories they cd to often. Other people set shell variables (Section 35.9) to hold the pathnames of directories they don't want to retype. But both of those methods make you remember directory abbreviations -- and make you put new aliases or shell variables in your shell startup files (Section 3.3) each time you want to add or change one. There's another way: the C shell's cdpath shell variable and the CDPATH variable in ksh, bash, and some versions of sh. (zsh understands both cdpath and CDPATH.) I'll use the term "cdpath" to talk about all shells.
When you type the command cd foo, the shell first tries to go to the exact pathname foo. If that doesn't work, and if foo is a relative pathname, the shell tries the same command from every directory listed in the cdpath. (If you use ksh or sh, see the note at the end of this article.)
Let's say that your home directory is /home/lisa and your current directory is somewhere else. Let's also say that your cdpath has the directories /home/lisa, /home/lisa/projects, and /books/troff. If your cd foo command doesn't work in your current directory, your shell will try cd /home/lisa/foo, cd /home/lisa/projects/foo, and cd /books/troff/foo, in that order. If the shell finds one, it shows the pathname:
% cd foo /home/lisa/foo %
If there is more than one matching directory, the shell uses the first match; if this isn't what you wanted, you can change the order of the directories in the cdpath.
Some Bourne shells don't show the directory name. All shells print an error, though, if they can't find any foo directory.
So, set your cdpath to a list of the parent directories that contain directories you might want to cd to. Don't list the exact directories -- list the parent directories (Section 1.16). This list goes in your .tcshrc, .cshrc, or .profile file. For example, lisa's .tcshrc could have:
set cdpath=(~ ~/projects /books/troff)
A Bourne shell user would have this in his .profile file:
CDPATH=:$HOME:$HOME/projects:/books/troff export CDPATH
A bash user might have it in her .bashrc or .bash_profile.
(If your system doesn't define $HOME, try $LOGDIR.)
NOTE: Note that the Bourne shell CDPATH in the above example starts with a colon (:) -- which, as in the PATH variable, is actually an empty entry (Section 35.6) that stands for "the current directory." Both the sh and ksh I tested required that. Without an empty entry, neither sh or ksh would cd into the current directory! (bash seemed to work like csh, though.) You could actually call this a feature. If there's no empty entry in CDPATH, a user has to use cd ./subdirname to go to a subdirectory of the current directory.
--JP and SJC
Copyright © 2003 O'Reilly & Associates. All rights reserved.