【问题标题】:Assigning to a positional parameter分配给位置参数
【发布时间】:2012-11-25 14:08:15
【问题描述】:

如何在 Bash 中为位置参数赋值?我想为默认参数赋值:

if [ -z "$4" ]; then
   4=$3
fi

表示4不是命令。

【问题讨论】:

    标签: bash positional-parameter


    【解决方案1】:

    set 内置是设置位置参数的唯一方法

    $ set -- this is a test
    $ echo $1
    this
    $ echo $4
    test
    

    -- 用于防止看起来像选项的东西(例如-x)。

    在你的情况下,你可能想要:

    if [ -z "$4" ]; then
       set -- "$1" "$2" "$3" "$3"
    fi
    

    但它可能会更清楚

    if [ -z "$4" ]; then
       # default the fourth option if it is null
       fourth="$3"
       set -- "$1" "$2" "$3" "$fourth"
    fi
    

    您可能还想查看参数计数$#,而不是测试-z

    【讨论】:

      【解决方案2】:

      你可以通过第四个参数再次调用你的脚本来做你想做的事:

      if [ -z "$4" ]; then
         $0 "$1" "$2" "$3" "$3"
         exit $?
      fi
      echo $4
      

      ./script.sh one two three这样调用上面的脚本会输出:

      三个

      【讨论】:

      • 如果通过 PATH 访问脚本,./$0 将不起作用,$0 本身应该没问题,这适用于 ./script/usr/local/bin/script 等。
      【解决方案3】:

      这可以通过直接分配到具有导出/导入类型机制的辅助数组来完成:

      set a b c "d e f" g h    
      thisArray=( "$@" )
      thisArray[3]=4
      set -- "${thisArray[@]}"
      echo "$@"
      

      输出'a b c 4 g h'

      【讨论】:

        猜你喜欢
        • 2021-10-17
        • 2017-05-11
        • 1970-01-01
        • 2013-06-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多