getopt命令可以接受一系列任意形式的命令行选项和参数,并自动将它们转换成适当的格式。
命令格式:
getopt optstring parameters
举例:
[root@localhost shell]# getopt ab:cd -a -b test1 -cd test2 test3
-a -b test1 -c -d -- test2 test3
上面定义了四个有效选项字母a,b,c,d,冒号被放在了字母b后面,因为b选项需要一个参数值。-cd选项自动分层两个单独的选项,并插入双破折线来分隔行中的额外参数。
如果指定了一个不在optstring中的选项,默认情况下,getopt会产生一条错误消息。
[root@localhost shell]# getopt ab:cd -a -b test1 -cde test2 test3
getopt:无效选项 -- e
-a -b test1 -c -d -- test2 test3
想忽略该错误提示,可以增加-q
参数
[root@localhost shell]# getopt -q ab:cd -a -b test1 -cde test2 test3
-a -b 'test1' -c -d -- 'test2' 'test3'
getopt扩展应用
[root@localhost shell]# cat test.sh
#!/bin/bash
set -- $(getopt -q ab:cd "$@")
while [ -n "$1" ]
do
case "$1" in
-a) echo "Found the -a option";;
-b) param=$2
echo "Found the -b option,with param value $param"
shift;;
-c) echo "Found the -c option";;
--) shift
break;;
*) echo "$1 is not an option";;
esac
shift
done
count=1
for param in "$@"
do
echo "Parameter #$count:$param"
count=$[ $count + 1 ]
done
[root@localhost shell]# ./test.sh -ac
Found the -a option
Found the -c option
[root@localhost shell]# ./test.sh -a -b test1 -cd test2 test3 test4
Found the -a option
Found the -b option,with param value 'test1'
Found the -c option
-d is not an option
Parameter #1:'test2'
Parameter #2:'test3'
Parameter #3:'test4'
缺点:不能很好的处理引号问题
[root@localhost shell]# ./test.sh -a -b test1 -cd "test2 test3" test4
Found the -a option
Found the -b option,with param value 'test1'
Found the -c option
-d is not an option
Parameter #1:'test2
Parameter #2:test3'
Parameter #3:'test4'
使用高级的getopts命令解决此问题。
getopts命令会用到两个环境变量,如果选项需要跟一个参数值,OPTARG
环境变量就会保存这个值。OPTIND
环境变量保存了参数列表中getopts正在处理的参数位置。
getopts命令格式
getopts optstring variable
如果选项字母要求有个参数值,就加一个冒号。要去掉错误消息,可以在optstring之前加一个冒号。
[root@localhost shell]# cat test.sh
#!/bin/bash
while getopts :ab:c opt
do
case "$opt" in
a) echo "Found the -a option" ;;
b) echo "Found the -b option, with value $OPTARG";;
c) echo "Found the -c option" ;;
*) echo "Unknown option: $opt";;
esac
done
shift $[ $OPTIND - 1 ]
count=1
for param in "$@"
do
echo "Parameter $count: $param"
count=$[ $count + 1 ]
done
测试之前的命令
[root@localhost shell]# ./test.sh -ab test1 -c
Found the -a option
Found the -b option, with value test1
Found the -c option
并且已经支持引号了
[root@localhost shell]# ./test.sh -b "test1 test2" -a
Found the -b option, with value test1 test2
Found the -a option
还可以不用加空格,getopts可以自动识别
[root@localhost shell]# ./test.sh -abtest1
Found the -a option
Found the -b option, with value test1
未定义的选项统一输出问号
[root@localhost shell]# ./test.sh -ade
Found the -a option
Unknown option: ?
Unknown option: ?
[root@localhost shell]# ./test.sh -a -b test1 -d test2 test3 test4
Found the -a option
Found the -b option, with value test1
Unknown option: ?
Parameter 1: test2
Parameter 2: test3
Parameter 3: test4