bash getopts 检查互斥参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21721070/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 09:32:28  来源:igfitidea点击:

getopts checking for mutually exclusive arguments

bashgetopts

提问by Chris Snow

I have a simple script (below) that has mutually exclusive arguments.

我有一个具有互斥参数的简单脚本(如下)。

The arguments for the script should be ./scriptname.sh -m|-d [-n], however, a user can run the script with ./scriptname.sh -m -dwhich is wrong.

脚本的参数应该是./scriptname.sh -m|-d [-n],但是,用户可以运行./scriptname.sh -m -d错误的脚本。

Question: how can I enforce that only one of the mutually exclusive arguments have been provided by the user?

问题:如何强制用户只提供一个互斥参数?

#!/bin/sh

usage() {
   cat <<EOF
Usage: 
./scriptname.sh -t desktop -n
-m|-d [-n] where: -m create minimal box -d create desktop box -n perform headless build EOF exit 0 } headless= buildtype= while getopts 'mdnh' flag; do case "$flag" in m) buildtype='minimal' ;; d) buildtype='desktop' ;; n) headless=1 ;; h) usage ;; \?) usage ;; *) usage ;; esac done [ -n "$buildtype" ] && usage

回答by anubhava

I can think of 2 ways:

我可以想到两种方法:

Accept an option like -t <argument>Where argument can be desktopor minimal

接受一个选项,例如-t <argument>Where 参数可以是desktopminimal

So your script will be called as:

所以你的脚本将被称为:

./scriptname.sh -t minimal -n

OR

或者

headless=
buildtype=

while getopts 'mdnh' flag; do
  case "$flag" in
    m) [ -n "$buildtype" ] && usage || buildtype='minimal' ;;
    d) [ -n "$buildtype" ] && usage || buildtype='desktop' ;;
    n) headless=1 ;;
    h) usage ;;
    \?) usage ;;
    *) usage ;;
  esac
done

Another alternativeis to enforce validation inside your script as this:

另一种选择是在脚本中强制执行验证,如下所示:

##代码##