In my .bash_profile I have the following lines:
PATHDIRS="
/usr/local/mysql/bin
/usr/local/share/python
/opt/local/bin
/opt/local/sbin
$HOME/bin"
for dir in $PATHDIRS
do
if [ -d $dir ]; then
export PATH=$PATH:$dir
fi
done
However I tried copying this to my .zshrc, and the $PATH is not being set.
First I put echo statements inside the “if directory exists” function and I found that the if statement was evaluating to false, even for directories that clearly existed.
Then I removed the directory-exists check, and the $PATH was being set incorrectly like this:
/usr/bin:/bin:/usr/sbin:/sbin:
/usr/local/bin
/opt/local/bin
/opt/local/sbin
/Volumes/Xshare/kburke/bin
/usr/local/Cellar/ruby/1.9.2-p290/bin
/Users/kevin/.gem/ruby/1.8/bin
/Users/kevin/bin
None of the programs in the bottom directories were being found or executed.
What am I doing wrong?
Unlike other shells, zsh does not perform word splitting or globbing after variable substitution. Thus
$PATHDIRSexpands to a single string containing exactly the value of the variable, and not to a list of strings containing each separate whitespace-delimited piece of the value.Using an array is the best way to express this (not only in zsh, but also in ksh and bash).
Since you probably aren’t going to refer to
pathdirslater, you might as well write it inline:There’s even a shorter way to express this: add all the directories you like to the
patharray, then select the ones that exist.The
Nglob qualifier selects only the matches that exist. Add the-/to the qualifier list (i.e.(-/N)or(N-/)) if you’re worried that one of the elements may be something other than a directory or a symbolic link to one (e.g. a broken symlink). The^parameter expansion flag ensures that the glob qualifier applies to each array element separately.You can also use the
Nqualifier to add an element only if it exists. Note that you need globbing to happen, sopath+=/usr/local/mysql/bin(N)wouldn’t work.