代码之家  ›  专栏  ›  技术社区  ›  tgoneil

带空格的命令行参数

  •  1
  • tgoneil  · 技术社区  · 8 年前

    使用包含空格的命令行参数调用shell脚本通常通过用引号括住参数来解决:

    getParams.sh 'one two' 'foo bar'
    

    生产:

    one two
    foo bar
    

    获取参数.sh:

    while [[ $# > 0 ]]
    do
        echo $1
        shift
    done
    

    但是,如果首先定义了一个shell变量来保存参数的值,例如:

    args="'one two' 'foo bar'"
    

    那么为什么:

    getParams.sh $args
    

    不识别包含分组参数的单引号?输出为:

    'one
    two'
    'three
    four'
    

    如何将包含空格的命令行参数存储到变量中,以便在调用getparams时,参数按照引用的参数分组,就像在原始示例中一样?

    1 回复  |  直到 8 年前
        1
  •  2
  •   user000001 jim mcnamara    8 年前

    使用数组:

    args=('one two' 'foo bar')
    
    getParams.sh "${args[@]}"
    

    使用 args="'one two' 'foo bar'" 不起作用,因为单引号在双引号内保留其文字值。

    保留参数中的多个空格(还可以处理特殊字符,如 * ,您应该引用您的变量:

    while [[ $# -gt 0 ]]
    do
        echo "$1"
        shift
    done