linux命令之getopts
getopts命令说明
getopts命令用于解析选项参数,被shell过程用于解析可定位的参数作为选项。
getopts内置变量说明
每次启动时,下一个待处
理的参数序号放入 shell 变量 OPTIND 中。OPTIND 变量在每
次 shell 或者 shell 脚本启动时都被初始化为1。当一个选项要
求有一个参数时,getopts 将参数放入 shell 变量 OPTARG
中。
getopts用法
getopts 选项字符串 名称 [参数]
#举个栗子
#!/bin/bash
# name:getopts_tesh.sh
while getopts ":a:b:" OPT;do
case $OPT in
a)
echo "The options is a."
echo "OPTARG:$OPTARG"
echo "OPTIND:$OPTIND"
;;
b) echo "The options is b."
echo "OPTARG:$OPTARG"
echo "OPTIND:$OPTIND"
;;
*) echo "Wrong option."
;;
esac
done
tianming@linux:~$ ./getopts_test.sh -a "aaaa" -b "bbbb"
The options is a.
OPTARG:aaaa
OPTIND:3
The options is b.
OPTARG:bbbb
OPTIND:5
注意的点
1.a前面的冒号的作用是去掉getopts遇到不存在的选项时抛出的不友好的错误;
./getopts_test.sh: 非法选项 -- d
Wrong option.
2.a和b后面的冒号是让a.b选项后面可以带参数
3.getopts不支持长选项
4.可以使用shift $((${OPTIND} - 1))把前面的选项和参数踢出去。