使用getopts处理长和短命令行选项 [英] Using getopts to process long and short command line options

查看:110
本文介绍了使用getopts处理长和短命令行选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望使用我的shell脚本来调用长短形式的命令行选项.

I wish to have long and short forms of command line options invoked using my shell script.

我知道可以使用getopts,但是像在Perl中一样,我无法对shell进行同样的操作.

I know that getopts can be used, but like in Perl, I have not been able to do the same with shell.

关于如何完成此操作的任何想法,这样我就可以使用以下选项:

Any ideas on how this can be done, so that I can use options like:

./shell.sh --copyfile abc.pl /tmp/
./shell.sh -c abc.pl /tmp/

在上面,这两个命令对我的shell来说意义相同,但是使用getopts,我无法实现这些功能?

In the above, both the commands mean the same thing to my shell, but using getopts, I have not been able to implement these?

推荐答案

可以考虑以下三种实现方式:

There are three implementations that may be considered:

  • 内置Bash的getopts.这不支持带有双破折号前缀的长选项名称.它仅支持单字符选项.

  • Bash builtin getopts. This does not support long option names with the double-dash prefix. It only supports single-character options.

BSD UNIX独立getopt命令的实现(MacOS使用的命令).这也不支持长选项.

BSD UNIX implementation of standalone getopt command (which is what MacOS uses). This does not support long options either.

独立getopt的GNU实现. GNU getopt(3) (由Linux上的命令行 getopt(1) )支持解析长选项.

GNU implementation of standalone getopt. GNU getopt(3) (used by the command-line getopt(1) on Linux) supports parsing long options.

其他一些答案显示了使用bash内置的getopts模仿长选项的解决方案.该解决方案实际上提供了一个简短的选项,其字符为-".因此,您将获得-"作为标志.然后,紧随其后的所有内容将变为OPTARG,然后使用嵌套的case测试OPTARG.

Some other answers show a solution for using the bash builtin getopts to mimic long options. That solution actually makes a short option whose character is "-". So you get "--" as the flag. Then anything following that becomes OPTARG, and you test the OPTARG with a nested case.

这很聪明,但附带警告:

This is clever, but it comes with caveats:

  • getopts无法执行opt规范.如果用户提供的选项无效,则不会返回错误.解析OPTARG时,您必须进行自己的错误检查.
  • OPTARG用于长选项名称,当长选项本身具有参数时,会使用法变得复杂.您最终不得不自己编写代码,作为额外的案例.
  • getopts can't enforce the opt spec. It can't return errors if the user supplies an invalid option. You have to do your own error-checking as you parse OPTARG.
  • OPTARG is used for the long option name, which complicates usage when your long option itself has an argument. You end up having to code that yourself as an additional case.

因此,尽管可以编写更多代码来解决对长选项缺乏支持的问题,但这需要做更多的工作,并且部分抵消了使用getopt解析器简化代码的目的.

So while it is possible to write more code to work around the lack of support for long options, this is a lot more work and partially defeats the purpose of using a getopt parser to simplify your code.

这篇关于使用getopts处理长和短命令行选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆