我目前的任务是为内部开发团队创建一些命令行帮助程序实用程序。但是,我想知道创建UNIX命令行工具的最佳实践。我尝试查看git源代码,以获取有关如何读取参数并相应显示消息的示例。但是,我正在寻找一个清晰的模板来创建工具,安全地读取参数以及如果用户输入了错误的参数或--help
想要显示帮助消息,则显示标准的“帮助” 消息。是否存在一个标准库,用于基于传递的参数读取-abcFGH
和--parameter
切换哪个进程开始?
命令行:
git
要么
git --help
输出:
usage: git [--version] [--exec-path[=<path>]] [--html-path] [--man-path] [--info-path]
[-p|--paginate|--no-pager] [--no-replace-objects] [--bare]
[--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>]
[-c name=value] [--help]
<command> [<args>]
...
命令行:
MyTool CommandName --CommandArgs
输出:
无论该特定命令做什么。
到目前为止,我的工作是:
码:
int main(int argc, char **argv)
{
if(argc < 2)
helpMessage();
char* commandParameter = argv[1];
if (strncmp(argv [1],"help", strlen(commandParameter)) == 0)
helpMessage();
else if (strncmp(argv [1],"pull", strlen(commandParameter)) == 0)
pull();
else
helpMessage();
}
理想的情况如下所示:
码:
int main(int argc, char **argv)
{
MagicParameters magicParameters = new MagicParameters(argv);
switch(magicParameters[1])
{
case command1:
Command1();
break;
case ...
case help:
default:
HelpMessage();
break;
}
}
getopt_long()是您要寻找的东西,这是最简单的用法示例:
static const struct option opts[] = {
{"version", no_argument, 0, 'v'},
{"help", no_argument, 0, 'h'},
{"message", required_argument, 0, 'm'},
/* And so on */
{0, 0, 0, 0 } /* Sentiel */
};
int optidx;
char c;
/* <option> and a ':' means it's marked as required_argument, make sure to do that.
* or optional_argument if it's optional.
* You can pass NULL as the last argument if it's not needed. */
while ((c = getopt_long(argc, argv, "vhm:", opts, &optidx)) != -1) {
switch (c) {
case 'v': print_version(); break;
case 'h': help(argv[0]); break;
case 'm': printf("%s\n", optarg); break;
case '?': help(argv[0]); return 1; /* getopt already thrown an error */
default:
if (optopt == 'c')
fprintf(stderr, "Option -%c requires an argument.\n",
optopt);
else if (isprint(optopt))
fprintf(stderr, "Unknown option -%c.\n", optopt);
else
fprintf(stderr, "Unknown option character '\\x%x'.\n",
optopt);
return 1;
}
}
/* Loop through other arguments ("leftovers"). */
while (optind < argc) {
/* whatever */;
++optind;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句