shell命令之——getopts

来源:互联网 发布:数据共享交换系统 编辑:程序博客网 时间:2024/04/28 20:20
1、getopts 简介

  由于shell命令行的灵活性,自己编写代码判断时,复杂度会比较高。使用内部命令 getopts 可以很方便地处理命令行参数。一般格式为:
getopts options variable

  getopts 的设计目标是在循环中运行,每次执行循环,getopts 就检查下一个命令行参数,并判断它是否合法。即检查参数是否以 - 开头,后面跟一个包含在 options 中的字母。如果是,就把匹配的选项字母存在指定的变量 variable 中,并返回退出状态0;如果 - 后面的字母没有包含在 options 中,就在 variable 中存入一个 ?,并返回退出状态0;如果命令行中已经没有参数,或者下一个参数不以 - 开头,就返回不为0的退出状态。

注:getopts 只针对带有“-”的选项参数起作用。

1)getopts 允许把选项堆叠在一起(如 -ms)

2)如要参数带有值,须在对应选项后加 :(如h后需加参数 h:ms)。此时选项和参数之间至少有一个空白字符分隔,这样的选项不能堆叠。

3)如果在需要参数的选项之后没有找到参数,它就在给定的变量中存入 ? ,并向标准错误中写入错误消息。否则将实际参数写入特殊变量 :OPTARG

4)另外一个特殊变量:OPTIND,反映下一个要处理的参数索引,初值是 1,每次执行 getopts 时都会更新。


2、实例:

#!/bin/bashwhile getopts h:ms optiondo        case "$option" in        h)                echo "option:h,value:$OPTARG"                echo "next arg index:$OPTIND";;        m)                echo "option:m,value:$OPTARG"                echo "next arg index:$OPTIND";;        s)                echo "option:s,value:$OPTARG"                echo "next arg index:$OPTIND";;        \?)                echo "usage error..."        esacdone

1)参数带有值的情况:

# sh test.sh -htest.sh: option requires an argument -- husage error...
由于选项参数h带有值,在脚本里使用“h:”的写法,所以在执行脚本的时候如果h参数没有值,就会报错。


2)参数带有值的情况:

# sh test.sh -h 100option:h,value:100next arg index:3
OPTIND反映下一个要处理的参数索引,初始值是1.


3)选项参数堆叠:

# sh test.sh -h 100 -msoption:h,value:100next arg index:3option:m,value:next arg index:3option:s,value:next arg index:4

# sh test.sh -h 100 -m -soption:h,value:100next arg index:3option:m,value:next arg index:4option:s,value:next arg index:5

4)实例4:

# sh test.sh -h 100 -m 200option:h,value:100next arg index:3option:m,value:next arg index:4
由于选项参数m没有在脚本中定义成"m:",所以即使在使用中加上值,也不会被识别

5)实例5:

# sh test.sh -h 100 -m 200 -soption:h,value:100next arg index:3option:m,value:next arg index:4
由于选项参数m没有在脚本中定义成"m:",遇到参数200时就不会被认为是选项参数m的值,反而会被当做没有“-”的参数对待,这时就结束命令,所以后面的-s选项参数也不会被识别。




0 0
原创粉丝点击