getopts 命令
该命令可以编写脚本,使控制多个命令行参数更加容易
格式:getopts option_str variable
vi getopts_exam1.sh
#!/bin/bash
#当输入的连字符不为“-a”或者“-b”时执行该函数
func()
{
echo " `basename $0` -[a b] args." >&2
exit 0
}
#使用getopts完成连接字符选择
while getopts "ab:" options
do
case $options in
a)
echo "You enter -a as an option."
;;
b)
echo "You enter -b as an option."
;;
\?)
func
;;
:)
echo "No argument value for option $OPTARG"
;;
esac
done
./getopts_exam1.sh -a -c
You enter -a as an option.
./getopts_exam1.sh: illegal option -- c
getopts_exam1.sh -[a b] args.
./getopts_exam2.sh -f file1
Option f is specified
Find the file file1.
./getopts_exam2.sh -h help
Option h has value help