【问题标题】:Accessing shell script arguments by index按索引访问 shell 脚本参数
【发布时间】:2013-06-04 11:08:45
【问题描述】:

我敢肯定,当您从事 shell 编程时,这很容易。 不幸的是,我不是,而且我过得很艰难......

我需要验证传递给 shell 脚本的参数。 我还想将传递的所有参数存储在一个数组中,因为稍后我需要进一步分离。

我有一个参数“-o”,后面必须跟 0 或 1。 因此,我想检查以下参数是否有效。 这是我尝试过的:

# Loop over all arguments
for i in "$@"
do
    # Check if there is a "-" as first character,
    # if so: it's a parameter
    str="$i"
    minus=${str:0:1}

    # Special case: -o is followed by 0 or 1
    # this parameter needs to be added, too
    if [ "$str" == "-o" ]
    then
        newIdx=`echo $((i+1))`   # <-- problem here: how can I access the script param by a generated index?
        par="$($newIdx)"

        if [[ "$par" != "0" || "$par" != "1" ]]
        then
            echo "script error: The -o parameter needs to be followed by 0 or 1"
            exit -1
        fi
        paramIndex=$((paramIndex+1))

    elif [ "$minus" == "-" ]
    then
        myArray[$paramIndex]="$i"
        paramIndex=$((paramIndex+1))
    fi
done

我尝试了各种方法,但都没有成功... 如果有人能阐明这一点,将不胜感激!

谢谢

【问题讨论】:

  • 使用while-loop 和shift 可能会更容易

标签: bash shell parameters scripting


【解决方案1】:

在bash 中,您可以使用间接参数扩展来访问任意位置参数。

$ set a b c
$ paramIndex=2
$ echo $2
b
$ echo ${!paramIndex}
b

【讨论】:

    【解决方案2】:

    没有方法可以访问for 中的下一个参数。

    1. 如何重写脚本以使用 getopt?

    2. 如果您不喜欢 getopt,请尝试使用 shift 重写您的脚本:

    
    while [ -n "$1" ]
    do
      str="$1"
      minus=${str:0:1}
      if [ "$str" == "-o" ]
      then
        shift
        par="$1"
    #  ...
      elif [ "$minus" == "-" ]
      then
        # append element into array
        myArray[${#myArray[@]}]="$str"
      fi
    
      shift
    done
    

    【讨论】:

    • 谢谢!我会在一分钟内调查它。让我感到困惑的是:我可以使用 $1, $2... 访问每个参数,但是当 parNum 是 shell 脚本中某处的简单变量时,我似乎无法执行 $parNum。对吗?
    • 我不知道通过存储在变量中的索引访问参数值的任何方法。但是您可以将参数复制到某个变量中并照常访问它的值:i=2; args=("$@"); echo "${args[$i]}"
    • 我支持使用getopts(内置的bash)或getopt(外部程序)的建议。
    • @loentar:感谢“附加到数组”的技巧。只是使用它;-)
    • @guitarflow: 有一种更简单的方法可以追加到数组:myArray+=("$str") - 一定要包含括号,否则它会追加到第一个元素而不是添加新元素到数组。
    猜你喜欢
    • 2016-08-16
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 2017-06-14
    • 1970-01-01
    • 2015-06-19
    • 2010-09-07
    • 1970-01-01
    相关资源
    最近更新 更多