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."
阅读(7764) | 评论(0) | 转发(1) |