首页 > 解决方案 > Bash getopt 接受多个参数

问题描述

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

链接中的解决方案对我不起作用。 Bash getopt 接受多个参数

代码: '''

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

'''

标签: bashshellunix

解决方案


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

更重要的是,您不需要调用shift. getopts负责消费和跳过每个选项和参数。

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

推荐阅读