命令概要
从Shell Script的命令行当中解析参数
getopts optstring name [arg...]
命令描述
optstring列出了对应的Shell Script可以识别的所有参数。比如,如果
Shell Script可以识别-a,-f以及-s参数,则optstring就是afs,如果对应
的参数后面还跟随一个值,则在相应的optstring后面加冒号。比如,a:fs
表示a参数后面会有一个值出现,-a value的形式。另外,getopts执行匹配
到a的时候,会把value存放在一个叫OPTARG的Shell Variable当中。如果
optstring是以冒号开头的,命令行当中出现了optstring当中没有的参数
将不会提示错误信息。
name表示的是参数的名称,每次执行getopts,会从命令行当中获取下一个
参数,然后存放到name当中。如果获取到的参数不在optstring当中列出,
则name的值被设置为?。
命令行当中的所有参数都有一个index,第一个参数从1开始,依次类推。
另外有一个名为OPTIND的Shell Variable存放下一个要处理的参数的index。
例子
#!/bin/bash
# getopts-test.sh
while getopts :d:s o
do
case "$o" in
d)
echo "d option value is $OPTARG"
echo "d option index is $(($OPTIND-1))"
;;
s)
echo "s option..."
echo "s option index is $(($OPTIND-1))"
;;
[?])
print "Usage: $0 [-s] [-d value] file ..."
exit 1
;;
esac
done
运行结果:
$ ./getopts-test.sh -d 8 -s
d option value is 8
d option index is 2
s option...
s option index is 3