4

我想在 shell 脚本中解析长选项。POSIX 仅提供getopts解析单字母选项。有谁知道在 shell 中实现长选项解析的可移植(POSIX)方法?我已经查看了autoconf生成configure脚本时的作用,但结果远非优雅。我可以接受只接受长选项的完整拼写。仍应允许单个字母选项,可能是分组。

我正在考虑一个 shell 函数,它采用空格分隔的 args 列表,形式为 option[=flags],其中标志表示该选项采用 arg 或可以指定多次。与它的 C 对应物不同,不需要区分字符串、整数和浮点数。

4

1 回答 1

2

针对可移植 shellgetopt_long命令的设计说明

我有一个程序getoptx可以使用单字母选项(因此它不是您问题的答案),但它可以正确处理带有空格的参数,而原始getopt命令(与 shell 内置命令相反getopts)没有。源代码中的规范说:

/*
** Usage: eval set -- $(getoptx abc: "$@")
**        eval set -- $(getoptx abc: -a -c 'a b c' -b abc 'd e f')
** The positional parameters are:
** $1 = "-a"
** $2 = "-c"
** $3 = "a b c"
** $4 = "-b"
** $5 = "--"
** $6 = "abc"
** $7 = "d e f"
**
** The advantage of this over the standard getopt program is that it handles
** spaces and other metacharacters (including single quotes) in the option
** values and other arguments.  The standard code does not!  The downside is
** the non-standard invocation syntax compared with:
**
**        set -- $(getopt abc: "$@")
*/

我推荐eval set -- $(getopt_long "$optspec" "$@")你的符号getopt_long

一个主要问题getopt_long是参数规范的复杂性——$optspec在示例中。

您可能想查看 Solaris CLIP(命令行界面范式)中使用的表示法;它使用单个字符串(如原始getopt()函数)来描述选项。(谷歌:“solaris clip 命令行界面范例”;仅使用“solaris clip”即可获得视频剪辑。)

该材料是源自 Sun 的部分示例getopt_clip()

/*

Example 2: Check Options and Arguments.

The following example parses a set of command line options and prints
messages to standard output for each option and argument that it
encounters.

This example can be expanded to be CLIP-compliant by substituting the
long string for the optstring argument:

While not encouraged by the CLIP specification, multiple long-option
aliases can also be assigned as shown in the following example:

:a(ascii)b(binary):(in-file)(input)o:(outfile)(output)V(version)?(help)

*/

static const char *arg0 = 0;

static void print_help(void)
{
    printf("Usage: %s [-a][-b][-V][-?][-f file][-o file][path ...]\n", arg0);
    printf("Usage: %s [-ascii][-binary][-version][-in-file file][-out-file file][path ...]\n", arg0);
    exit(0);
}

static const char optstr[] =
    ":a(ascii)b(binary)f:(in-file)o:(out-file)V(version)?(help)";

int main(int argc, char **argv)
{
    int c;
    char *filename;

    arg0 = argv[0];
    while ((c = getopt_clip(argc, argv, optstr)) != -1)
    {
        ...
    }
    ...
}
于 2012-08-07T14:40:21.860 回答