shell中getopt/getopts的使用

getopts配合case来进行操做时有两个隐含变量:一个是OPTARG,用来取当前选项的值,另一个是OPTIND,表明当前选项在参数列表中的位移。OPTIND是一个特殊的变量,它的初始值是1,每次getopts处理完一个命令参数后就递增它,获得getopts要处理的下一个参数。    下面的例子可参考: >cattest4 #!/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老是存储原始$*中下一个要处理的元素位置。 whilegetopts ":a:bc" opt  #第一个冒号表示忽略错误;字符后面的冒号表示该选项必须有本身的参数 代码实例(getopts.sh): echo $* whilegetopts ":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   下面是getopt处理长短参数选项的一个实例。 aflag=no bflag=no cargument=none   #options may be followed by one colon to indicate they have a required argument if!options=$(getopt-o abc:-l along,blong,clong:--"$@") then     # something went wrong, getopt will put outan error message for us     exit 1 fi   set--$options   while[$#-gt 0 ] do     case$1 in     -a|--along)aflag="yes";;     -b|--blong)bflag="yes";;     # foroptions with required arguments, an additional shift is required     -c|--clong)cargument="$2";shift;;     (--)shift;break;;     (-*)echo "$0: error - unrecognizedoption $1"1>&2;exit 1;;     (*)break;;     esac     shift done   说明: -o后面是短选项列表,abc:说明a, b都是不带参数的,而c必须带一个参数,好比-a -c copt -l后面是长选项列表,aaa:,bb,cc:表示aaa和cc必须带参数,而bb不带参数,好比--aaa=aaaopt --bb
相关文章
相关标签/搜索