Chinaunix首页 | 论坛 | 博客
  • 博客访问: 567499
  • 博文数量: 84
  • 博客积分: 1529
  • 博客等级: 上尉
  • 技术积分: 1482
  • 用 户 组: 普通用户
  • 注册时间: 2011-01-27 17:57
文章分类

全部博文(84)

文章存档

2014年(7)

2013年(9)

2012年(20)

2011年(48)

分类: Python/Ruby

2011-06-21 16:07:38

getopts配合case来进行操作时有两个隐含变量:一个是OPTARG,用来取当前选项的值,另外一个是OPTIND,代表当前选项在参数列表中的位移。OPTIND是一个特殊的变量,它的初始值是1,每次getopts处理完一个命令参数后就递增它,得到getopts要处理的下一个参数。

   下面的例子可参考:

>cat test4
#!/bin/bash
while getopts "ab:cd:" Option
# b and d take arguments
#
do
case $Option in
a) echo -e "a = $OPTIND";;
b) echo -e "b = $OPTIND $OPTARG";;
c) echo -e "c = $OPTIND";;
d) echo -e "d = $OPTIND $OPTARG";;
esac
done
shift $(($OPTIND - 1))

>sh test4 -a -b foo -cd bar
a = 2
b = 4 foo
c = 4
d = 6 bar

>sh test4 -ab foo
a = 1
b = 3 foo

>sh test4 -a -c
a = 2
c = 3

getopts (Shell内置命令)
处理命令行参数是一个相似而又复杂的事情,为此,C提供了getopt/getopt_long等函数,C++的boost提供了Options库,在shell中,处理此事的是getopts和getopt.

先说一下getopts/getopt的区别吧,getopt是个外部binary文件,而getopts是shell builtin。

[admin@intlqa142055x ~]$ type getopt
getopt is /usr/bin/getopt
[admin@intlqa142055x ~]$ type getopts
getopts is a shell builtin
getopts不能直接处理长的选项(如:--prefix=/home等)
关于getopts的使用方法,可以man bash  搜索getopts
getopts 有两个参数,第一个参数是一个字符串,包括字符和“:”,每一个字符都是一个有效的选项,如果字符后面带有“:”,表示这个字符有自己的参数。 getopts从命令中获取这些参数,并且删去了“-”,并将其赋值在第二个参数中,如果带有自己参数,这个参数赋值在“OPTARG”中。提供getopts的shell内置了OPTARG这个变变,getopts修改了这个变量。
这里变量$OPTARG存储相应选项的参数,而$OPTIND总是存储原始$*中下一个要处理的元素位置。
while getopts ":a:bc" opt  #第一个冒号表示忽略错误;字符后面的冒号表示该选项必须有自己的参数
代码实例(getopts.sh):
 
echo $*
while getopts ":a:bc" opt
do
        case $opt in
                a ) echo $OPTARG
                    echo $OPTIND;;
                b ) echo "b $OPTIND";;
                c ) echo "c $OPTIND";;
                ? ) echo "error"
                    exit 1;;
        esac
done
echo $OPTIND
shift $(($OPTIND - 1))
#通过shift $(($OPTIND - 1))的处理,$*中就只保留了除去选项内容的参数,可以在其后进行正常的shell编程处理了。
echo $0
echo $*
执行命令:./getopts.sh -a 11 -b -c
-a 11 -b -c
11
3
b 4
c 5
5
./getopts.sh
阅读(966) | 评论(0) | 转发(0) |
0

上一篇:shell 十三问

下一篇:for 和 if 返回值

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