【问题标题】:Portable getopt_long equivalent for use in shell scripting用于 shell 脚本的便携式 getopt_long 等效项
【发布时间】:2012-07-30 13:14:27
【问题描述】:

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

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

【问题讨论】:

标签: shell posix getopt


【解决方案1】:

便携式 shell getopt_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: "$@")
*/

我建议您的getopt_long 使用eval set -- $(getopt_long "$optspec" "$@") 表示法。

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)
    {
        ...
    }
    ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-04
    • 2016-04-16
    相关资源
    最近更新 更多