构建包含空格的参数列表

时间:2009-01-04 19:04:46

标签: bash arguments whitespace

在bash中,可以转义包含空格的参数。

foo "a string"

这也适用于命令或函数的参数:

bar() {
    foo "$@"
}

bar "a string"

到目前为止一切顺利,但如果我想在调用foo之前操纵参数怎么办?

这不起作用:

bar() {
    for arg in "$@"
    do
        args="$args \"prefix $arg\""
    done

    # Everything looks good ...
    echo $args

    # ... but it isn't.
    foo $args

    # foo "$args" would just be silly
}

bar a b c

那么当参数包含空格时,如何构建参数列表?

5 个答案:

答案 0 :(得分:16)

至少有两种方法可以做到这一点:

  1. 使用数组并使用"${array[@]}"展开

    bar() {
        local i=0 args=()
        for arg in "$@"
        do
            args[$i]="prefix $arg"
            ((++i))
        done
    
        foo "${args[@]}"
    }
    

    那么,我们学到了什么? "${array[@]}" ${array[*]} "$@"$*的对象是eval

  2. 或者,如果您不想使用数组,则需要使用bar() { local args=() for arg in "$@" do args="$args \"prefix $arg\"" done eval foo $args }

    {{1}}

答案 1 :(得分:4)

这是一个较短的版本,不需要使用数字索引:

(例如:构建find命令的参数)

dir=$1
shift
for f in "$@" ; do
    args+=(-iname "*$f*")
done
find "$dir" "${args[@]}"

答案 2 :(得分:2)

使用arrays(Bash中hidden features之一)。

答案 3 :(得分:0)

您可以按照建议使用数组,并更改细节。调用foo的行应该是

 foo "${args[@]}"

答案 4 :(得分:0)

我也有这个问题。我正在编写一个bash脚本来备份我的Windows计算机上的重要文件(cygwin)。我也尝试了阵列方法,但仍然存在一些问题。我不确定我是如何修复它的,但这里是我的代码中很重要的部分,以防它对你有所帮助。

WORK="d:\Work Documents\*"
#   prompt and 7zip each file
for x in $SVN $WEB1 $WEB2 "$WORK" $GRAPHICS $W_SQL
do
    echo "Add $x to archive? (y/n)"
    read DO
    if [ "$DO" == "y" ]; then
        echo "compressing $x"
        7zip a $W_OUTPUT "$x"
    fi
    echo ""
done
相关问题