shell中getopt/getopts的使用


  下面的例子可参考:
>cattest4
#!/bin/bash
while getopts "ab:cd:" Option
# b and d take arguments
#
do
case $Option in
a) echo -e "a = $OPTIND";;
b) echo -e "b = $OPTIND $OPTARG";;
c) echo -e "c = $OPTIND";;
d) echo -e "d = $OPTIND $OPTARG";;
esac
done
shift $(($OPTIND - 1))


>sh test4 -a -b foo -cd bar
a = 2
b = 4 foo
c = 4
d = 6 bar


>sh test4 -ab foo
a = 1
b = 3 foo


>sh test4 -a -c
a = 2
c = 3
 
getopts(Shell内置命令)
处理命令行参数是一个相似而又复杂的事情,为此,C提供了getopt/getopt_long等函数,C++的boost提供了Options库,在shell中,处理此事的是getopts和getopt.
先说一下getopts/getopt的区别吧,getopt是个外部binary文件,而getopts是shell builtin。
[admin@intlqa142055x~]$ type getopt
getopt is /usr/bin/getopt
[admin@intlqa142055x ~]$ type getopts
getopts is a shell builtin
 
getopts不能直接处理长的选项(如:--prefix=/home等)
关于getopts的使用方法,可以man bash 搜索getopts
getopts 有两个参数,第一个参数是一个字符串,包括字符和“:”,每一个字符都是一个有效的选项,如果字符后面带有“:”,表示这个字符有自己的参数。getopts从命令中获取这些参数,并且删去了“-”,并将其赋值在第二个参数中,如果带有自己参数,这个参数赋值在“OPTARG”中。提供getopts的shell内置了OPTARG这个变变,getopts修改了这个变量。
这里变量$OPTARG存储相应选项的参数,而$OPTIND总是存储原始$*中下一个要处理的元素位置。
whilegetopts ":a:bc" opt  #第一个冒号表示忽略错误;字符后面的冒号表示该选项必须有自己的参数
代码实例(getopts.sh):
echo $*
whilegetopts ":a:bc" opt
do
        case $opt in
                a ) echo $OPTARG
                    echo $OPTIND;;
                b ) echo "b$OPTIND";;
                c ) echo "c$OPTIND";;
                ? ) echo "error"
                    exit 1;;
        esac
done
echo$OPTIND
shift$(($OPTIND - 1))
#通过shift $(($OPTIND - 1))的处理,$*中就只保留了除去选项内容的参数,可以在其后进行正常的shell编程处理了。
echo $0
echo $*
 
执行命令:./getopts.sh -a 11 -b -c
-a 11 -b-c
11
3
b 4
c 5
5
./getopts.sh
 
下面是getopt处理长短参数选项的一个实例。
aflag=no
bflag=no
cargument=none
 
#options may be followed by one colon to indicate they have a required argument
if!options=$(getopt-o abc:-l along,blong,clong:--"$@")
then
    # something went wrong, getopt will put outan error message for us
    exit 1
fi
 
set--$options
 
while[$#-gt 0 ]
do
    case$1 in
    -a|--along)aflag="yes";;
    -b|--blong)bflag="yes";;
    # foroptions with required arguments, an additional shift is required
    -c|--clong)cargument="$2";shift;;
    (--)shift;break;;
    (-*)echo "$0: error - unrecognizedoption $1"1>&2;exit 1;;
    (*)break;;
    esac
    shift
done
 
说明:
-o后面是短选项列表,abc:说明a, b都是不带参数的,而c必须带一个参数,比如-a -c copt
-l后面是长选项列表,aaa:,bb,cc:表示aaa和cc必须带参数,而bb不带参数,比如--aaa=aaaopt --bb

转载于:https://my.oschina.net/HankCN/blog/116120

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值