如何在 ZSH 中编辑路径变量 [英] How to edit path variable in ZSH
问题描述
在我的 .bash_profile 中,我有以下几行:
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
但是我尝试将其复制到我的 .zshrc 中,并且没有设置 $PATH
.
However I tried copying this to my .zshrc, and the $PATH
is not being set.
首先,我将 echo
语句放入if directory exists"函数中,我发现 if 语句的计算结果为 false,即使对于明显存在的目录也是如此.
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.
然后我删除了目录存在检查,并且 $PATH
被错误地设置如下:
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?
推荐答案
与其他 shell 不同,zsh 在变量替换后不执行分词或通配.因此,$PATHDIRS
扩展为包含变量值的单个字符串,而不是包含每个单独的以空格分隔的值的字符串列表.
Unlike other shells, zsh does not perform word splitting or globbing after variable substitution. Thus $PATHDIRS
expands 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.
使用数组是表达这一点的最佳方式(不仅在 zsh 中,而且在 ksh 和 bash 中).
Using an array is the best way to express this (not only in zsh, but also in ksh and bash).
pathdirs=(
/usr/local/mysql/bin
…
~/bin
)
for dir in $pathdirs; do
if [ -d $dir ]; then
path+=$dir
fi
done
由于您以后可能不会引用pathdirs
,您不妨将其写成内联:
Since you probably aren't going to refer to pathdirs
later, you might as well write it inline:
for dir in \
/usr/local/mysql/bin \
… \
~/bin
; do
if [[ -d $dir ]]; then path+=$dir; fi
done
还有一种更短的表达方式:将您喜欢的所有目录添加到 path
数组中,然后选择存在的目录.
There's even a shorter way to express this: add all the directories you like to the path
array, then select the ones that exist.
path+=/usr/local/mysql/bin
…
path=($^path(N))
N
glob 限定符 仅选择匹配项那个存在.如果您担心,将 -/
添加到限定符列表(即 (-/N)
或 (N-/)
)元素的一部分可能不是目录或指向一个的符号链接(例如损坏的符号链接).^
参数扩展标志确保glob限定符分别应用于每个数组元素.
The N
glob 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.
您还可以使用 N
限定符添加仅存在的元素.请注意,您需要进行通配,因此 path+=/usr/local/mysql/bin(N)
将不起作用.
You can also use the N
qualifier to add an element only if it exists. Note that you need globbing to happen, so path+=/usr/local/mysql/bin(N)
wouldn't work.
path+=(/usr/local/bin/mysql/bin(N-/))
这篇关于如何在 ZSH 中编辑路径变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!