【问题标题】:Storing bash script argument with multiple values使用多个值存储 bash 脚本参数
【发布时间】:2017-09-19 20:40:40
【问题描述】:

我希望能够将输入解析为如下所示的 bash shell 脚本。

myscript.sh --casename obstacle1 --output en --variables v P pResidualTT

迄今为止我最好的方法失败了,因为最后一个参数有多个值。第一个参数应该只有 1 个值,但第三个参数可以有任何大于 1 的值。有没有办法指定从第三个参数到下一组“--”的所有内容都应该被抓取?我将假设用户不受约束按我显示的顺序提供参数。

casename=notset
variables=notset
output_format=notset
while [[ $# -gt 1 ]]
do
    key="$1"
    case $key in
        --casename)
        casename=$2
        shift
        ;;
        --output)
        output_format=$2
        shift
        ;;
        --variables)
        variables="$2"
        shift
        ;;
        *)
        echo configure option \'$1\' not understood!
        echo use ./configure --help to see correct usage!
        exit -1
        break
        ;;

    esac
    shift
done

echo $casename
echo $output_format
echo $variables

【问题讨论】:

  • 在您的示例中,--variables 是否有 2 个或 3 个值?如果答案是2,您希望脚本如何区分参数值(vP)和非参数值(pResidualTT)?您打算如何稍后在脚本中引用多值参数...循环遍历一组值?解析连接值的变量?
  • 第三个参数将被转储到一个变量中并直接传递给另一个脚本,该脚本知道如何解析第三个参数的各个组件。

标签: bash shell


【解决方案1】:

一种常规做法(如果你将要这样做)是关闭多个参数。那就是:

variables=( )
case $key in
  --variables)
    while (( "$#" >= 2 )) && ! [[ $2 = --* ]]; do
      variables+=( "$2" )
      shift
    done
    ;;
esac

也就是说,建立您的调用约定更为常见,因此调用者会为每个以下变量传递一个 -V--variable 参数——也就是说,类似于:

myscript --casename obstacle1 --output en -V=v -V=p -V=pResidualTT

...在这种情况下,您只需要:

case $key in
  -V=*|--variable=*) variables+=( "${1#*=}" );;
  -V|--variable)   variables+=( "$2" ); shift;;
esac

【讨论】:

    猜你喜欢
    • 2022-10-23
    • 1970-01-01
    • 2023-03-04
    • 2015-08-06
    • 1970-01-01
    • 2011-09-30
    • 2022-10-23
    • 2021-11-04
    • 1970-01-01
    相关资源
    最近更新 更多