【问题标题】:How can I prevent an option that requires an argument to use the next option when no argument is given?当没有给出参数时,如何防止需要参数的选项使用下一个选项?
【发布时间】:2012-06-13 16:37:45
【问题描述】:

我在 test.sh 中有以下代码:

while getopts "f:i:" opt; do
  case $opt in
  f)
    echo $OPTARG
  i) echo $OPTARG

现在如果我运行 ./test.sh -f 我会得到错误:

option requires an argument -- i

但是,当我运行 ./test.sh -f -i test 时,它会回显 -i。

我知道这是因为它只是将下一个参数用空格分隔,但是有没有简单的方法来处理这个问题?

我可以做if [ $OPTARG == "-i" ]; then exit 1,但我希望当我有多种选择时有一种更简单的方法。

【问题讨论】:

    标签: shell sh getopts


    【解决方案1】:

    如果您使用 getopts,它有自己的方式。放手去做。

    毕竟,谁说选项的参数不能以破折号开头?如果是文件名,用户可能希望文件名以破折号开头。如果是数字,可能是负数。

    【讨论】:

      猜你喜欢
      • 2018-11-08
      • 1970-01-01
      • 2023-03-21
      • 2016-04-06
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多