linux getopt命令,shell脚本之getopt命令

getopt

分析传递到脚本命令行的最前有力的工具,该命令与getopt外部命令和C语言中的getopt的作用是相同的,能

分配多个参数草脚本中。

使用两个隐含的变量,$OPTIND(OPTion INDex)即参数指针和选项索引 ,$OPTARG(OPTion ARGument)选项

参数,

在声明标签中,选项名后面的冒号用来提示这个选项名已经分配了一个参数。

使用注意事项:

通过命令行传递到脚本中的参数前边必须加上一个dash(-)符号,只有这样,getopt才会认为这个参数是一个选项

getopt命令不处理不带dash符号的参数。

#!/bin/bash

#ex33.sh:Exercising getopts and OPTIND

#

#Here wo  observe how 'getopt' processes command-line arguments to script.

#The argument are parsed as "options"(flags) and associated arguments.

#Try invoking this scripts with:

#    'scriptname -mn'

#    'scriptname -oq qOption'(qOption canbe some arbitrary string.)

#    'scriptname -qXXX -r'

#

#    'scriptname -qr'

#+        -Unexpected result,takes "r" as the argument to option "q"

#    'scriptname -q -r'

#+        -Unexpected result,same as above

#    'scriptname -mnop -mnop'    -Unexpect result

#    (OPTIND is unreliable at stating where an option come from.)

#

#    If an option expects an argument ("flag:"),then it will grab

#+    whatever is next on the command-line.

NO_ARGS=0

E_OPTERROR=65

if [ $# -eq "$NO_ARGS" ]        #script invoked with no command-line args?

then

echo "Usage:`basename $0` options (-mnopqrs)"

exit $E_OPTERROR        #Exit and explain usage.

#Usage:scriptname -options

#Note:dash (-) necessary

fi

while getopts ":mnopq:rs" Option

do

case $Option in

m    ) echo "Scenario #1:option -m- [OPTIND=${OPTIND}]"

;;

n|o    ) echo "Scenario #2:option -$Option- [optind=${OPTIND}]"

;;

p    ) echo "Scenario #3: option -p- [OPTIND=${OPTIND}]"

;;

q    ) echo "Scenario #4: option -q-with argument \"$OPTIND\" [OPTIND=${OPTIND}]"

;;

#    Note that option 'q' must have an associated argument,

#+    otherwise it falls through to the default.

r|s    ) echo "Scenario #5: option -$Option- [OPTIND=${OPTIND}]"

;;

*    ) echo "Unimplemented option chosen."        #Default.

;;

esac

done

shift $(($OPTIND-1))

#Decrements the argument pointer soit points to  next argument.

#$1 now references the first non-option item supplied on the command-line

#+if one exists.

exit $?

#The getopts mechanism allow one to specify: scriptname -mnop -mnop

#+but there is no reliable way to differentiate what came from where

#+by using OPTIND."

阅读(6466) | 评论(0) | 转发(1) |

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值