getopts可以编写脚本,使控制多个命令行参数更加容易。getopts用于形成命令行处理标准形式。一般来讲,脚本应具有确认带有多个选项的命令文件标准格式的能力。
getopts一般格式为:getopts option_string variable
getopts一般格式为:getopts option_string variable
getopts读取option_string,获知脚本中使用了有效选项,getopts查看所有以连字符“-”开头的参数,将其视为选项。有时有必要在脚本中指定命令行选项取值。getopts为此提供了一种方式,即在option_string中将一个冒号“:”放在选项后,如getopts ahfvc: OPTION,使用选项取值时,必须使用变量OPTARG保存该值。
!/bin/ksh
#getopts
#set the vars
ALL=false
HELP=false
FILE=false
VERBOSE=false
COPIES=0
while getopts ahfgvc: OPTION
do
case $OPTION in
a)
ALL=true
echo "ALL is $ALL"
;;
h)
HELP=true
echo "HELP is $HELP"
;;
f)
FILE=true
echo "FILE is $FILE"
;;
v)
VERBOSE=true
echo "VERBOSE is $VERBOSE"
;;
c)
COPIES=$OPTARG
echo "COPIES IS $COPIES"
;;
\?)
echo "`basename $0` -[a h f v] -[c values] file" >&2
;;
esac
done