在我以前的.bashrc
中,我有一个简短的部分如下:
PATH2ADD_SCRIPTBIN="/home/foo/bar/scriptbin"
PATH2ADD_PYTHONSTUFF="/home/foo/bar/pythonprojects"
PATH2ADDLIST="$PATH2ADD_SCRIPTBIN $PATH2ADD_PYTHONSTUFF"
for PATH2ADD in $PATH2ADDLIST; do
if [ -z `echo $PATH | grep "$PATH2ADD"` ]; then
export PATH=$PATH:$PATH2ADD
echo "Added '$PATH2ADD' to the PATH."
fi
done
在Bash中,这个工作方式与预期一致:它附加了我在$PATH2ADDLIST
中包含的路径(如果它们还没有出现在路径中)(在我意识到每次获取路径有多大之后我必须这样做我正在寻找我的.bashrc
)。输出(当提供的路径不存在时)如下:
Added '/home/foo/bar/scriptbin' to the PATH.
Added '/home/foo/bar/pythonprojects' to the PATH.
但是,我最近切换到Zsh
的神奇土地,现在完全相同的文字行产生了这个结果:
Added '/home/foo/bar/scriptbin /home/foo/bar/pythonprojects' to the PATH.
现在我很确定这是因为Zsh
参与扩展的方式有所不同,或者它与Zsh
更改for
的方式有关循环,但我不确定如何解决这个问题。
可能有人有一些见解吗?
答案 0 :(得分:3)
使用数组存储这些变量,即
PATH2ADD_SCRIPTBIN="/home/foo/bar/scriptbin"
PATH2ADD_PYTHONSTUFF="/home/foo/bar/pythonprojects"
# Initializing 'PATH2ADDLIST' as an array with the 2 variables
# to make the looping easier
PATH2ADDLIST=("${PATH2ADD_SCRIPTBIN}" "${PATH2ADD_PYTHONSTUFF}")
# Looping through the array contents
for PATH2ADD in "${PATH2ADDLIST[@]}"
do
# Using the exit code of 'grep' directly with a '!' negate
# condition
if ! echo "$PATH" | grep -q "$PATH2ADD"
then
export PATH=$PATH:$PATH2ADD
echo "Added '$PATH2ADD' to the PATH."
fi
done
这样可以使zsh
和bash
更兼容。两个壳上的样品干运行
# With interpreter set to /bin/zsh
zsh script.sh
Added '/home/foo/bar/scriptbin' to the PATH.
Added '/home/foo/bar/pythonprojects' to the PATH.
并在bash
bash script.sh
Added '/home/foo/bar/scriptbin' to the PATH.
Added '/home/foo/bar/pythonprojects' to the PATH.
答案 1 :(得分:1)
zsh
有一些功能可以让您更轻松地更新路径。一,有一个数组参数path
反映PATH
:对另一个的更改反映在另一个中。二,声明该变量以消除重复。你可以简单地写
path+=("/home/foo/bar/scriptbin" "/home/foo/bar/pythonprojects")
并且每个新路径都会附加到path
(如果它尚不存在)。
如果您想要更多地控制它们的添加顺序(例如,如果您想要前置),您可以使用以下样式:
path=( "/home/foo/bar/scriptbin"
$path
"/home/foo/bar/pythonprojects"
)
(请注意,数组参数的扩展包括 all 元素,而不仅仅是bash
中的第一个元素。)