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

查看:33
本文介绍了使用 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.

独立 getopt 命令的 BSD UNIX 实现(这是 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)(由命令行使用 getopt(1) 在 Linux 上)支持解析长选项.

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天全站免登陆