getopts配合case来进行操作时有两个隐含变量:一个是OPTARG,用来取当前选项的值,另外一个是OPTIND,代表下一个要处理的元素位置。
如test4 -a -b foo -cd bar
1 2 3 4 5
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的使用方法,可以man bash
getopts 有两个参数,第一个参数是一个字符串,包括字符和“:”,每一个字符都是一个有效的选项,如果字符后面带有“:”,表示这个字符有自己的参数。 getopts从命令中获取这些参数,并且删去了“-”,并将其赋值在第二个参数中,如果带有自己参数,这个参数赋值在“OPTARG”中。 提供getopts的shell内置了OPTARG这个变变,getopts修改了这个变量。
这里变量$OPTARG存储相应选项的参数,而$OPTIND总是存储原始$*中下一个要处理的元素位置。
while getopts ":a:bc" opt
代码实例(getopts.sh):
echo $* while getopts ":a:bc" opt do done echo $OPTIND shift $(($OPTIND - 1)) #通过shift $(($OPTIND - 1))的处理,$*中就只保留了除去选项内容的参数,可以在其后进行正常的shell编程处理了。 echo $0 echo $* |
-a 11 -b -c
11
3
b 4
c 5
5
./getopts.sh
此处为$*的空值