Linux bash,获取getopt默认参数

Linux bash, getting getopt default parameters

我正在尝试编写一个中等难度的 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 值设置为某些东西总是会产生默认值)。

OS: Linux, getopt -V=getopt from util-linux 2.27

感谢任何帮助:)

查看手册页:

A simple short option is a '-' followed by a short option character. If the option has a required argument, it may be written directly after the option character or as the next parameter (i.e. separated by whitespace on the command line). If the option has an optional argument, it must be written directly after the option character if present.

所以你想要

$ 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' --