【问题标题】:Getopts same flag two times两次获取相同的标志
【发布时间】:2018-03-13 07:02:43
【问题描述】:

您好,我有一个基本问题,但我找不到合适的答案

我有这个代码:

while getopts :weco:r:u:hP: ARG; do
  case $ARG in
             .
             .
             .

    h)  #set option "h" - show help;
      help
      ;;
    P)  #set option "P" - select Printer;
      PRINTER=$OPTARG
      ;;
    \?) #unrecognized option - show help
      echo -e \\n"Option not recognized."
      help
      ;;
  esac
done

现在我想使用“-P”两次,如果你使用“-P PRINTER”,它会使用给定的打印机,但如果你只使用“-P”,它会使用从文件中读取的默认值。

我可以这样管理吗?抱歉,如果这是正确答案,我现在无法测试。

while getopts :weco:r:u:hP:P ARG; do
  case $ARG in
             .
             .
             .

    h)  #set option "h" - show help;
      help
      ;;
    P)  #set option to use default
      PRINTER=BLAFOO
    P)  #set option "P" - select Printer;
      PRINTER=$OPTARG
      ;;
    \?) #unrecognized option - show help
      echo -e \\n"Option not recognized."
      help
      ;;
  esac
done

【问题讨论】:

标签: bash shell printing getopts


【解决方案1】:

我建议你重新编写自己的参数解析器,因为 getopts 不支持你想要的。

while true; do
  case $1 in
    -h)  #set option "h" - show help;
      echo help
      shift
      ;;
    -P)  #set option "P" - select Printer;
      shift
      case $1 in
      ""|-*)
        PRINTER=BLAFOO
        ;;
      *)
        PRINTER=$1
        shift
        ;;
      esac
      # echo PRINTER=$PRINTER
      ;;
    -*|*)  #unrecognized option - show help
      echo -e \\n"Option not recognized."
      echo help
      break ;;
  esac
done

【讨论】:

  • @Nico,对你有用吗?如果可以,请提供一些反馈。
猜你喜欢
  • 2013-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-04
  • 1970-01-01
相关资源
最近更新 更多