getopt: parse command options
格式:getopt options optstring parameters
可以用set命令使getopt命令处理后的命令行选项和参数。set命令用双破折号可以命令行参数替换成set命令的命令行的值。
用法:set -- `getopt -q ab:cd "$@"` 现在原始的命令行参数变量的值会被getopt命令的输出替换,而getopt已经为提供了格式化好的命令行参数。
$cat test.sh
#!/bin/bash
set -- `getopt -q ab:c "$@"`
while [ -n "$1" ]
do
case "$1" in
-a) echo "Found the -a option";;
-b) param="$2"
echo "Found the -b option, with parameter value $param"
shift;;
-c) echo "Fond the -c option";;
--) shift
break;;
*) echo "$1 is not an option";;
esac
shift
done
count=1
for param in "$@"
do
echo "Parmaeter #$count: $parma"
count=$[ $count + 1 ]
done
脚本可以处理复杂的参数。
$./test.sh -ac
Found the -a option
Found the -c option
$./test.sh -a -b test1 -cd test2 test3 test4
Found the -a option
Found the -b option, with parameter value 'test1'
Found the -c option
Parameter #1: 'test2'
Parameter #2: 'test3'
Parameter #3: 'test4'
但是getopt不能处理带空格的参数值。e.g.
$./test.sh -a -b test1 -cd “test2 test3” test4
Found the -a option
Found the -b option, with parameter value 'test1'
Found the -c option
Parameter #1: 'test2'
Parameter #2: 'test3'
Parameter #3: 'test4'
getopts能够解决上面的这个问题。
getopts: getopts optstring name [arg] Parse option arguments.
getopts是bash shell的builtin命令。getopts每次只处理一个命令行上的检测到的参数,处理完所有的参数后,它会退出并返回一个大于零的退出状态码。所以可以在循环中解析所有命令行参数。
格式:getopts optring variable optstring和getopt中optstring残不多,如果要去掉错误消息的话可以在optstring之前加一个冒号,getopts命令将当前参数保存在命令行中定义的variable中。
getopts命令会用到两个环境变量。如果选项需要一个参数值,OPTARG环境变量就会保存这个值。OPTIND环境变量保存了参数列表中getopts正在出来的参数位置。
$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
$./test.sh -ab test1 -c
Found the -a option
Found the -b option, with value test1
Found the -c option
$./test.sh -ab "test1 test2 " -c
Found the -a option
Found the -b option, with value test1 test2
Found the -c option
$./test.sh -abtest1
Found the -a option
Found the -b option, with the value test1 #另一个功能就是将选项字母和参数值放在一起使用,不用加空格
g etopts命令在解析命令行选项时,它会移除开头的单破折号,所以在这里的case定义中不需要单破折号。
getopts能够正确处理有空格的命令行选项。
getopts能够将命令行上找到的所有未定义的选项统一输出成问号。
$./test.sh -d
Unknown option: ?
getopts命令知道什么时候停止处理选项,并将参数留给你处理。在getopts处理每个选项时,它会将OPTIND环境变量值增一。在getopts完成处理时,你可以将OPTIND值和shift命令一起使用来移动参数:
$cat test.sh
#!/bin/bash
while getopts :ab:cd 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";;
d) echo "Found the -d option";;
*) echo "Unknown option: $opt";;
esac
done
shift $[ $OPTIND - 1 ]
count=1
for param in "$@"
do
echo "Parameter $count: $param"
count=$[ $count + 1 ]
done
$./test.sh -a -b test1 -d test2 test3 test4
Found the -a option
Found the -b option, with value test1
Found th -d option
Parameter 1: test2
Parameter 2: test3
Parameter 3: test4