【问题标题】:Handle Bash getopts option with one of other options使用其他选项之一处理 Bash getopts 选项
【发布时间】:2019-11-15 08:45:51
【问题描述】:

我当前的 Bash 脚本如下所示。到目前为止,除了选项-g 外,它都在工作。我希望这个选项是可选的,但如果没有 -c-n 中的任何一个,它就不能使用。

所以我的意思是:

  • -g 完全是可选的
  • 但是,如果给出了它,那么 -c-n 也必须存在。

很遗憾,我不知道该怎么做。

while getopts ':cniahg:' opt; do
  case $opt in
  g) DAYS_GRACE_PERIOD=$OPTARG ;;
  c) prune_containers ;;
  i) prune_images ;;
  n) prune_networks ;;
  a)
    prune_containers
    prune_networks
    prune_images
    ;;
  :) echo "Invalid option: $OPTARG requires an argument" 1>&2 ;;
  h) print_usage ;;
  \?) print_usage ;;
  *) print_usage ;;
  esac
done
shift $((OPTIND - 1))

【问题讨论】:

    标签: bash getopts


    【解决方案1】:

    -g 选项是可选的,但它不能在没有任何 -c 或 -n 的情况下使用。

    在一个变量中存储选项c,在另一个变量中使用选项n,在另一个变量中使用选项g。解析选项后,使用变量检查条件。

    g_used=false c_used=false n_used=false
    while .....
       g) g_used=true; ...
       c) c_used=true; ...
       n) n_used=true; ...
    ....
    
    # something like that
    if "$g_used"; then
        if ! "$c_used" || ! "$n_used"; then
          echo "ERROR: -g option was used, but -c or -n option was not used"
        fi
    fi
    
    # ex. move the execution of actions after the option parsing
    if "$c_used"; then
        prune_containers
    fi
    if "$n_used"; then
        prune_networks
    fi
    

    看起来您的循环通过解析参数执行操作。在您的解析选项循环中,您可以设置与每个选项关联的变量,然后在循环之后根据“所有选项的状态”执行操作。在循环之后,因为您将拥有所有使用的选项的“全局”视图,因此基于多个标志进行解析和做出决策会更容易。

    【讨论】:

      猜你喜欢
      • 2021-06-23
      • 2015-07-16
      • 2010-09-28
      • 2013-04-17
      • 2012-08-14
      • 2021-04-29
      • 2019-08-25
      相关资源
      最近更新 更多