Chinaunix首页 | 论坛 | 博客
  • 博客访问: 370471
  • 博文数量: 94
  • 博客积分: 3421
  • 博客等级: 中校
  • 技术积分: 919
  • 用 户 组: 普通用户
  • 注册时间: 2009-11-18 16:27
文章分类

全部博文(94)

文章存档

2015年(8)

2013年(6)

2012年(26)

2011年(8)

2010年(26)

2009年(20)

我的朋友

分类: Python/Ruby

2012-03-18 09:02:42

++++++SHELL++++
查看一个文件的信息
1) type   (getopts/getopt 一个是shell内建,一个是外部的小程序)
type getopts (shell builtin)
type getopt

getopts optstring name [args]

点击(此处)折叠或打开

  1. echo $*
  2. while getopts ":a:bc" opt
  3. do
  4. case $opt in
  5. a) echo "a" $opt $OPTIND $OPTARG;;
  6. b) echo 'b' $opt $OPTIND $OPTARG;;
  7. c) echo 'c' $opt $OPTIND $OPTARG;;
  8. ?) echo "error" exit 1;;
  9. esac
  10. done
  11. echo $OPTIND
  12. shift $(($OPTIND-1))
  13. echo $0
  14. echo $*
对于getopts要有几个地方要清楚
0)随后的第一个参数一定要跟-
$ ./getopts.sh abc (由于没跟-,导致参数无法分析)
abc
1
./getopts.sh
abc
 ./getopts.sh abc -b (无法分析)
abc
1
./getopts.sh
abc

./getopts.sh -abc (可以分析)
-abc
a a 2 bc
2
./getopts.sh

1) OPTIND变量是存储参数位置的index. 初始值为,一个参数前后如果都要空格,包括选项的参数,那它就会加1
$ ./getopts.sh -a 11 -b -c  (按照常理来说的话,-b应该是第二个参数,$OPTIND为3,可结果为4)
-a 11 -b -c
a a 3 11
b b 4
c c 5
5
./getopts.sh -a11 -b -c (11前后没空格了,-b对应的$OPTIND为3)
-a11 -b -c
a a 2 11
b b 3
c c 4
4
./getopts.sh
2)OPTARG 目的是存选项后的参数值的。ms这个不受空格的影响。 只要是"optstring"中含有:就会把其后的值当作选项来存。
./getopts.sh -a -b -c (-b 当作了-a 选项的参数了)
-a -b -c
a a 3 -b
c c 4
4
./getopts.sh

./getopts.sh -a11 -b -c (11仍然是-a选项的参数值)
-a11 -b -c
a a 2 11
b b 3
c c 4
4
./getopts.sh

++++++c program++++
表头文件
#include
定义函数
int getopt(int argc,char * const argv[ ],const char * optstring);
     返回值
      
如果找到符合的参数则返回此参数字母,
       如果参数不包含在参数optstring 的选项字母则返回“?”字符,分析结束则返回-1 (待写)

点击(此处)折叠或打开

  1. #include<unistd.h>
  2. #include <stdio.h>
  3. int main(int argc, char *argv[])
  4. {
  5. char ch;
  6. opterr = 0;
  7. int i=0;
  8. printf("argc=%d \n",argc );
  9. for (i=0; i < argc; i++)
  10. {
  11.    printf("argv[%d]=%s\n",i, argv[i]);
  12. }
  13. argc=1;
  14. while ((ch=getopt(argc, argv,"a:b"))!=-1)
  15. {
  16.    printf("optind: %d\n", optind);
  17.    switch (ch)
  18.    {
  19.      case 'a':
  20.       printf("option a is %s\n",optarg);
  21.       break;
  22.     case 'b':
  23.       printf("option b is recevied\n");
  24.       break;
  25.     default:
  26.       printf("other option :%c\n",ch);
  27.    }
  28. }
  29.  printf("optopt +%c\n",optopt);
  30.  return 0;
  31. }
在调试时发现./getopt -a:cb 不经入while,需要进一步的研究。
另外一点需要说明的是optind/optarg/optopt都是一些在头文件定义的变量。我们可以直接使用的。

阅读(1443) | 评论(0) | 转发(0) |
0

上一篇:程序栈的大小

下一篇:存储系统及I/O空间

给主人留下些什么吧!~~