【问题标题】:Bash getopt to accept multiple parameters [duplicate]Bash getopt接受多个参数[重复]
【发布时间】:2021-10-16 16:08:52
【问题描述】:

我正在编写一个使用 getopt 来解析参数的脚本。到目前为止我的解决方案只接受一个参数。有没有办法让这个解决方案接受多个参数(例如,'-f 和 -l)?

链接中的解决方案对我不起作用。 Bash getopt accepting multiple parameters

代码: '''

while getopts "f:l:" option; do
      case "${option}" in
          f) firstdate=${OPTARG}
             shift
             ;;
          l) lastdate=${OPTORG}
             ;;
         *)
            echo "UsageInfo"
            exit 1
            ;;
       esac
      shift
    done

'''

【问题讨论】:

  • 删除循环内的shifts。如果要在处理完选项参数后删除它们,请在循环结束后添加 shift $((OPTIND-1))

标签: bash shell unix


【解决方案1】:

首先,您有一个错字:OPTORG 应该是 OPTARG

更重要的是,您不需要调用shiftgetopts 负责处理和跳过每个选项和参数。

while getopts "f:l:" option; do
  case "${option}" in
      f) firstdate=${OPTARG} ;;
      l) lastdate=${OPTARG} ;;
      *)
        echo "UsageInfo"
        exit 1
        ;;
   esac
done

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-28
    • 2015-01-12
    • 2023-03-16
    • 2012-05-21
    • 2021-10-07
    • 1970-01-01
    相关资源
    最近更新 更多