@@@ getopts命令
getopts命令内建于bash shell。
getopts命令的格式如右:getopts optstring variable
optstring定义的内容与getopt命令完全相同。
但是其输出内容与getopt命令完全不同。
例子如下:
$ getopt ab:cd -a -b test1 -cd test2 test3 ###getopt输出例
-a -b test1 -c -d -- test2 test3
$ getopts ab:cd -a -b test1 -cd test2 test3 ###getopts输出例1
-bash: getopts: `-a': not a valid identifier
$ getopts ab:cd -a
-bash: getopts: `-a': not a valid identifier ###getopts输出例2
$ getopts ab:cd a ###getopts输出例3
###回车后为不输出任何内容
为什么会由以上结果,我也不清楚。希望有懂的朋友可以助我解惑。
@@@ getopts在shell脚本中的用法
以下是一个简单的例子:
$ cat getopts.sh
#!/bin/bash
# simple demonstration of the getopts command
#
echo
while getopts ab:c opt ###通过whlie循环将选项通过getopts格式化成opt变量
do
case "$opt" in
a) echo "Found the -a option" ;;
b) echo "Found the -b option, with value $OPTARG";; ###$OPTARG变量指的是选项后的参数
c) echo "Found the -c option" ;;
*) echo "Unknown option: $opt";;
esac
done
$
输出结果:
$ ./getopts.sh -ab test1 -c
Found the -a option
Found the -b option, with value test1
Found the -c option
$ ./getopts.sh -b "test1 test2" -a ###可以完美识别''双引号
Found the -b option, with value test1 test2
Found the -a option
$
$ ./getopts.sh -d #输入未定义的选项后显示的错误信息
cat: invalid option -- 'd'
Try 'cat --help' for more information.
$ ./getopts.sh -d #在ab:c之前加上:变成:ab:c以后getopts能
Unknown option: ? #将所有未定义的选项统一输出成问号
以上,是我今天的学习总结。