getopts

  getopts命令顺序的对现有的shell参数变量进行处理,每调用一次getopts,他只处理在命令中检测到的参数中的一个,处理完所有的参数后,以大于0的退出状态退出,因此,getopts非常适宜用在循环中解析所有命令参数
getopts命令的格式为 getopts optstring variable 
  其中optstring值与getopt命令中使用的相似,在选项字符串中列出邮箱选项字母,如果选项字母需要参数放在命令行中定义的variable中getopts命令使用两个环境变量,环境变量OPTARG包含的值表示getopts停止处理时在参数列表中的位置,这样,处理完选项后可以继续处理其它命令行参数.

  文件名为 test19.sh 

 1 #!/bin/bash
 2 # sinmple demonstration of the getopts command
 3 
 4 while getopts :ab:c opt
 5 do
 6   case "$opt" in
 7   a) echo "Found the -a option" ;;
 8   b) echo "Found the -b option, with value $OPTARG";;
 9   c) echo "Found the -c option" ;;
10   *) echo "Unknow option :$opt";;
11  esac
12 done

运行 sh test19.sh -ab test1 -c 

输出:

Found the -a option
Found the -b option, with value test1
Found the -c option

 

  while语句定义getopts命令,指定要查找哪些命令行选项以及每次迭代中存储它们的变量名,在本例中,可以看到case语句的使用有些特别之处,当getopts命令解析命令行选项时,会将打头的破折号去掉,所以在case定义中不需要破折号
  getopts命令具有许多很好的特性,首先,现在可以在参数值中包含空格

运行 sh test19.sh -b "test1 test2" -a 

输出:

Found the -b option, with value test1 test2
Found the -a option

另一个好特性是选项字母和参数值中间可以没有空格

运行 sh test19.sh -abtest1 

输出:

Found the -a option
Found the -b option, with value test1

getopts命令正确的将-b选项后面的test1值解析出来,getopts命令还有一个好特性就是将在命令行中找到的未定义的选项都绑定为一个单一的输出--问号

运行 sh test19.sh -d 

输出: Unknow option :? 

 

  getopts命令知道核实停止处理选项,将参数留给你处理,getopts每个处理选项,环境变量OPTIND的值会增加1,当达到getopts处理的末尾时,可以使用shift命令和OPTIND值进行操作来移动到参数

文件名: test20.sh 

#!/bin/bash
# processing options and parameters with getopts

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 "Unknow option:$opt";;
esac
done
shift $[ $OPTIND - 1 ]

count=1
for param in "$@"
do 
  echo "Parameter $count:$param"
  count=$[ $count + 1 ]
done

运行 sh test20.sh -a -b test1 -d test2 test3 test4 

输出:

Found the -a option
Found the -b option ,with value test1
Found the -d option
Parameter 1:test2
Parameter 2:test3
Parameter 3:test4

 

posted @ 2015-09-08 10:39  todaytoday  阅读(218)  评论(0编辑  收藏  举报