linux开发 -- 命令行参数解析 getopt

来源:互联网 发布:mac os server工具 编辑:程序博客网 时间:2024/05/21 07:11
linux大部分工具都是以命令行方式运行,因此都需要对命令行参数解析,它们大多都是用相同的解析方法!(有点废话)再次记录下来!省得以后再查。

大部分软件都是用getopt系列函数解析命令行,glibc中就提供了该函数的实现,即使没有依赖glibc,其他软件包也会提供相应的实现。

短格式的参数解析:
int getopt(int argc, char * const argv[], const char *optstring);
argc: main函数传入的参数个数
argv: main函数传入的参数指针
optstring: 一个用来描述接受的参数字符串,每个字符代表一个选项,其中需要带参数的加":"符号,例如"a:bc",表示接受a,b,c三个选项,其中a带参数 调用如 cmd -a 123 -b -c
返回值: 返回解析到的选项的字符如'a',如果全部解析完毕返回-1. 解析到不在optstring中列出的返回'?'

全局变量:
    char *optarg 选项附带的参数的指针
    int optind  下一个被处理的argv下标
  1. int opt = 0;
  2. while ((opt = getopt(argc, argv, "a:bc")) != -1) {
  3.     switch (opt) {
  4.     case 'a':
  5.         printf("paramenter is a = %s", optarg);
  6.         break;
  7.     case 'b':
  8.         printf("paramenter is b");
  9.         break;
  10.     case 'c':
  11.         printf("paramenter is c");
  12.     case '?':
  13.         printf("unkown paramenter");
  14.     }
  15. }
解析装格式选项:
int getopt_long(int argc, char * const argv[], const char *optstring, const struct option *longopts, int *longindex);
支持 --arg=param --arg parm的格式,也支持短格式
longopts option的数组
struct option {
   const char *name  选项的长名字
   int has_arg   指定是否带参数 no_argument 不带参数 required_argument 带参数 optional_argument 可选参数
   int *flag  如果不为NULL,则当解析到该选项时将val设置为该值
   int val 解析到该选项时 函数返回val
}
}
longindex 如果不为NULL 被设置为解析到的长选项索引

int getopt_long(int argc, char * const argv[], const char *optstring, const struct option *longopts, int *longindex);
支持 -arg=param -arg param


脚本中解析命令行选项
getopts

  1. while getopts a:bc opt; do
  2.    case $opt
  3.     a) echo $OPTARG ;;
  4.     b) ;;
  5.     c) ;;
  6.     ?) ;;
  7.    esac
  8. done

原创粉丝点击