针对可移植 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)
{
...
}
...
}