【问题标题】:Using two argument values for an option with getopt对带有 getopt 的选项使用两个参数值
【发布时间】:2021-12-27 13:17:42
【问题描述】:

使用getopt 已有一段时间了。我正在研究一个选项有两个参数值的可能性。这很好吗?可以用getopt 做到这一点。举个例子会有所帮助。

做了一些测试,发现这样做

myfunc -S 13 21

给予

opts:  -S '13' -- '21'

在哪里

opts=$( getopt -o "$shortopts" -l "$longopts" -n "${0##*/}" -- "$@" )

因此 getopt 无法接受myfunc -S 13 21

【问题讨论】:

  • 一个你想要实现的例子也会有所帮助.....

标签: bash getopt


【解决方案1】:

我就是这样处理事情的

 while (( $# > 0 )); do
   case $1 in
    ("-S"|"--seam")
      [[ "$2" = +([[:digit:]]) ]] && { sp="$2" ; shift ; }
      [[ "$2" = +([[:digit:]]) ]] && { sq="$2" ; shift ; }
      ;;
   esac
 done

【讨论】:

    【解决方案2】:

    看这里Retrieving multiple arguments for a single option using getopts in Bash 基本上说你可以在命令行中多次添加一个选项 像这样: myscript.sh -x value1 -x value2 当您遍历选项时,您可以在每次getopt 遇到该选项时附加它。这是一个例子:

    #!/bin/bash
    $XVALUE
    while getopts "x:" arg; do
      case $arg in
        x)
          XVALUE="$XVALUE$OPTARG"
          ;;
      esac
    done
    
    echo "Values: $XVALUE"
    # ./myscript -x a -x b
    # Values: ab
    

    【讨论】:

    • 当然这可以使用数组或分隔符来改进,这是一个幼稚的例子,可以帮助你理解基本思想,顺便避免重复提问
    • OP 写的是getopt 而不是getopts。不确定它会改变什么
    • 正如Bash FAQ 所说:getopt(1) is a massively broken tool. You shoud never use it
    猜你喜欢
    • 2014-03-22
    • 2021-06-24
    • 2016-11-15
    • 2014-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-29
    相关资源
    最近更新 更多