getopts
getopts是linux系统中的一个内置变量,一般用在循环中。每当执行循环时,getopts都会检查下一个命令选项,如果这些选项出现在option中,则表示是合法选项,并将这些合法选项保存在VARIABLE这个变量中,否则不是合法选项。
语法格式:
getopts [option[:]] [DESCPRITION] VARIABLE
option:表示为某个脚本可以使用的选项
":":如果某个选项(option)后面出现了冒号(":"),则表示这个选项后面可以接参数
VARIABLE:表示将某个选项保存在变量VARIABLE中
例:
#!/bin/bash
#
NO_ARGS=0
E_OPTERROR=65
if [ $# -eq "$NO_ARGS" ];then
echo "Usage: `basename $0` options (-mnopqrs)"
exit $E_OPTERROR
fi
while getopts ":mnopq:rs" Option
do
case $Option in
m ) echo "Scenario #1: option -m- [OPTIND=${OPTIND}]";;
n | o ) echo "Scenario #2: option -$Option- [OPTIND=${OPTIND}]";;
p ) echo "Scenario #3: option -p- [OPTIND=${OPTIND}]";;
q ) echo "Scenario #4: option -q- with argument \"$OPTARG\" [OPTIND=${OPTIND}]";;
r | s ) echo "Scenario #5: option -$Option-";;
* ) echo "Unimplemented option chosen.";;
esac
done
shift $(($OPTIND - 1))
exit 0
这里":"表示,执行此脚本时,选项-q后面必须要加参数
[root@localhost aaa]# sh 1.sh -q
Unimplemented option chosen.
[root@localhost aaa]# sh 1.sh -q 123
Scenario #4: option -q- with argument "123" [OPTIND=3]
getopts包含两个内置变量OPTARG和OPTIND
OPTARG:将选项后面的参数保存在这个变量当中
OPTIND:表示命令行的下一个选项或参数的索引(我的理解就是位置变量的位置)
例:
#!/bin/bash
#
while getopts ':b:d:' OPT &> /dev/null
do
case $OPT in
b)
echo "The options is b"
echo "argument is $OPTARG";;
d)
echo "The options is d"
echo "argument is $OPTARG";;
*)
echo "Wrong Options"
exit 7 ;;
esac
done
echo $OPTIND
shift $[$OPTIND-1]
echo $1
执行脚本时,显示的结果如下
[root@localhost aaa]# sh 1.sh -d nice fixnale
The options is d
nice
3
fixnale
当输入-d时,$OPT=d,$OPTARG=“nice”
这里有一个选项(-d)和一个参数(‘nice’),$OPTIND指向命令行中下一个选项或参数的索引位置,因此这里即为3。
shift $[$OPTIND-1]表示将文件名前面的选项和参数踢掉
下面的例子用于理解$OPTIND
#!/bin/bash
#
while getopts ':wpfb:d:' OPT &> /dev/null
do
case $OPT in
w)
echo "The options is w"
echo "next index is $OPTIND";;
p)
echo "The options is p"
echo "next index is $OPTIND";;
f)
echo "The options is f"
echo "next index is $OPTIND";;
b)
echo "The options is b"
echo "argument is $OPTARG"
echo "next index is $OPTIND";;
d)
echo "The options is d"
echo "argument is $OPTARG"
echo "next index is $OPTIND";;
*)
echo "Wrong Options"
exit 7 ;;
esac
done
echo $OPTIND
shift $[$OPTIND-1]
echo $1
执行方式一:-wpf
[root@localhost aaa]# sh 1.sh -wpf
The options is w
next index is 1
The options is p
next index is 1
The options is f
next index is 2
2
执行方式二:-w -p -f
[root@localhost aaa]# sh 1.sh -w -p -f
The options is w
next index is 2
The options is p
next index is 3
The options is f
next index is 4
4
执行方式三:-wpfd abc 2.txt
[root@localhost aaa]# sh 1.sh -wpfd abc 2.txt
The options is w
next index is 1
The options is p
next index is 1
The options is f
next index is 1
The options is d
argument is abc
next index is 3
3
2.txt
执行方式四:-w -p -f -d abc 2.txt
[root@localhost aaa]# sh 1.sh -w -p -f -d abc 2.txt
The options is w
next index is 2
The options is p
next index is 3
The options is f
next index is 4
The options is d
argument is abc
next index is 6
6
2.txt