-
#!/bin/bash
-
#testopt.sh
-
if [[ $# -lt 1 ]];then
-
echo "Usage:`basename $0` [-p] [-q value] [-m value] "
-
exit 1
-
fi
-
echo "The value of OPTIND is :$OPTIND"
-
#注意看第一个冒号,前面加冒号,代表开启静默模式,抑制正常的错误信息,而由脚本自己处理
-
while getopts ":pq:m:" optname
-
do
-
echo "The value of optname is : $optname"
-
case $optname in
-
"p")
-
echo "Option $optname is specified"
-
;;
-
"q")
-
echo "Option $optname has args $OPTARG"
-
;;
-
"m")
-
echo "Option $optname has args $OPTARG"
-
;;
-
"?")
-
echo "Unknown option $OPTARG"
-
;;
-
":")
-
echo "No argument value for option $OPTARG"
-
;;
-
*)
-
echo "Wrong parameter"
-
;;
-
esac
-
echo "The value of OPTIND is :$OPTIND"
-
done
执行结果如下
[ L:tmp$ ]sh testopt.sh -r -p -q -d -m //共五个
The value of OPTIND is :1 //OPTIND为变量,初值为1,之后代表指向下一个索引的值
The value of optname is : ? //由于开启静默模式,因此无效的选项(比如-r)被当作“?”处理,即$optname的值为?,而$OPTARG的值为r
Unknown option r
The value of OPTIND is :2
The value of optname is : p
Option p is specified
The value of OPTIND is :3
The value of optname is : q //第二个和第三个冒号代表该选项后面需要接参数。当-q后直接接-d时,会把-d当作-q的参数来处理
Option q has args -d
The value of OPTIND is :5 //此处指向第五个选项-m
The value of optname is : : //由于m后接冒号,代表需要跟参数,而此时无参数,$optname的值被当作": "来处理
No argument value for option m
The value of OPTIND is :6
修改脚本去掉第一个冒号,及告诉getopts关闭静默,执行结果如下:
The value of OPTIND is :1
testopt.sh: illegal option -- r
The value of optname is : ? //关闭静默模式后,无效的选项被当作?来处理
Unknown option
The value of OPTIND is :2
The value of optname is : p
Option p is specified
The value of OPTIND is :3
The value of optname is : q
Option q has args -d
The value of OPTIND is :5
testopt.sh: option requires an argument -- m
The value of optname is : ?
Unknown option //关闭静默模式后,无效的参数也被当作?来处理
The value of OPTIND is :6
当什么参数都不添加时,是不会进入循环的,因此最好加上下面的判断
if [[ $# -lt 1 ]];then
echo "Usage:`basename $0` [-p] [-q value] [-m value] "
exit 1
fi
阅读(2661) | 评论(0) | 转发(0) |