【问题标题】:Linux bash, getting getopt default parametersLinux bash,获取getopt默认参数
【发布时间】:2015-10-15 14:09:02
【问题描述】:

我正在尝试编写一个难度适中的 bash 程序,但不知何故我无法解析命令行参数并使用 getopt 设置默认参数。

Getopt 以某种方式忽略了可选参数,将它们设置在 -- 之后,表示参数结束。

简单测试,其中需要 l(list):

getopt -s bash -o l: -l list: -- -l test

生产:

-l 'test' --

如果我将 l(list) 定义为可选,则输出为:

getopt -s bash -o l:: -l list:: -- -l test

-l '' -- 'test'

我使用this example 作为基础,但在我的测试中,即使这个脚本也不能按预期工作(将 arga 值设置为某个值总是会产生默认值)。

操作系统:Linux,getopt -V=getopt 来自 util-linux 2.27

任何帮助表示赞赏:)

【问题讨论】:

  • IIRC getopts 仅适用于短选项,不适用于长选项。该教程中的代码正在执行自己的解析以迭代选项。在 SO(以及网络的其余部分)上几乎肯定有很多关于此的问题/答案/示例。

标签: linux bash shell getopt


【解决方案1】:

查看手册页:

一个简单的短选项是一个'-'后跟一个短选项字符。如果该选项有一个必需的 参数,它可以直接写在选项字符之后或作为下一个参数(即在命令行上用空格分隔)。 如果选项有可选参数,则必须直接写在选项字符之后(如果存在)

所以你想要

$ getopt -s bash -o l:: -l list:: -- -ltest
 -l 'test' --

同样,对于可选长参数,您必须以特定方式提供参数:

必填

$ getopt -s bash -o l: -l list: -- --list foo
 --list 'foo' --
$ getopt -s bash -o l: -l list: -- --list=foo
 --list 'foo' --

可选

$ getopt -s bash -o l:: -l list:: -- --list foo
 --list '' -- 'foo'
$ getopt -s bash -o l:: -l list:: -- --list=foo
 --list 'foo' --

【讨论】:

  • 感谢您指出手册中的相关部分。我阅读了手册,但似乎我略读了它,太长了。 getopt 在强制参数和可选参数之间的风格似乎有点不一致。似乎我有 Idée fixe,linuxland 中支持长参数的所有程序都使用 program --param <arg|undefined>
  • 感谢您直言不讳。我什至没有注意到差异——这些天我没有做足够的 bash 来记住细节,而不是不断地输入 man foo
猜你喜欢
  • 1970-01-01
  • 2018-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-16
  • 2015-12-10
相关资源
最近更新 更多