zsh循环遍历多个参数

时间:2017-02-05 02:48:33

标签: bash shell zsh variable-expansion

在我以前的.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的方式有关循环,但我不确定如何解决这个问题。

可能有人有一些见解吗?

2 个答案:

答案 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

这样可以使zshbash更兼容。两个壳上的样品干运行

# 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中的第一个元素。)