简体   繁体   English

bash编程中的getopts

[英]getopts in bash programming

当我使用'while getopts d:n:OPTION'时-我怎么知道我只有无效的选项,如果是,那后面还有一个参数?

You know you have an invalid option because the return value is '?'. 您知道您的选项无效,因为返回值为'?'。

Either: 或者:

  • You can't tell whether it had an argument because the option was invalid. 您无法判断它是否有参数,因为该选项无效。

Or: 要么:

  • You have to look at the next argument and see whether it starts with a dash. 您必须查看下一个参数,看看它是否以短划线开头。

The heuristic in the 'Or' option is imperfect. “或”选项中的启发式方法是不完善的。 With option bundling, I could write: 通过选项捆绑,我可以写:

command -xbf/fidget
  1. If the getopts option string is 'xf:' , then the 'b' is the invalid option. 如果getopts选项字符串为'xf:' ,则'b'为无效选项。
  2. If the getopts option string is 'xbf:' , then there would be an option 'f' and the option argument '/fidget' after the valid option 'b'. 如果getopts选项字符串为'xbf:' ,则有效选项'b'之后将有一个选项'f'和选项参数'/ fidget'。
  3. If the getopts option string is 'xb:f: ', then the option argument for 'b' would be 'f/fidget'. 如果getopts选项字符串是'xb:f: ',则'b'的选项参数将是'f / fidget'。

I think the 'either' attitude is correct - you cannot tell. 我认为“任何一种”态度都是正确的-您无法分辨。


Code fragment from a command called 'rcsunco' - to cancel RCS checkouts (and written at a time when I was reluctantly moving off SCCS): 来自名为“ rcsunco”的命令的代码片段-取消RCS检出(并在我勉强离开SCCS时编写):

remove=yes
keep=no
get=no
quiet=

while getopts gknqrV opt
do
        case $opt in
        V)  echo "`basename $0 .sh`: RCSUNCO Version $Revision: 2.1 $ ($Date: 2002/08/03 07:41:00 $)" |
            rcsmunger
            exit 0;;
        g)  get=yes;;
        k)  keep=yes;;
        n)  remove=no;;
        q)  quiet=-q;;
        r)  remove=yes;;
        *)  echo "Usage: `basename $0 .sh` [-{n|g}][-{r|k}] file [...]" 1>&2
            exit 1;;
        esac
done

shift $(($OPTIND-1))

These days, I'd used the 'balanced parentheses' notation in the 'case': 这些天来,我在“案例”中使用了“平衡括号”表示法:

        (q) quiet=-q;;

Also note that I do not explicitly test which option is returned - I let the catchall '*' case deal. 还要注意,我没有明确测试返回哪个选项-我让所有的'*'案例都处理了。 I also observe that the usage message is not complete (no '-V' or '-q' documented), and the code is old enough that I haven't added a '-h' for help option. 我还观察到用法消息不完整(没有记录“ -V”或“ -q”),并且代码足够老,以至于我没有添加“ -h”作为帮助选项。 The script 'rcsmunger' replaces ' $Revision 2.1 $ ' with just ' 2.1 ', more like the way SCCS replaces '%I%' with '2.1'. 脚本“ rcsmunger”仅将“ $Revision 2.1 $ ”替换$Revision 2.1 $2.1 ”,更像SCCS用“ 2.1”替换“%I%”的方式。

无效的选项将带有问号?...如果有问号,则对命令行参数的IIRC处理将停止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM