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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值