Handle Bash getopts选项和其他选项之一

问题描述 投票:0回答:1

我当前的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个回答
2
投票

-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

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

© www.soinside.com 2019 - 2024. All rights reserved.