bash/shell 解析命令行参数工具:getopts/getopt

bash 脚本中,简单点的参数选项,咱们能够直接用位置参数 $1 $2 这样来获取处理了,例以下面这段代码片断: html

optionParam=$1
baseHdfsPath=$2
echo $optionParam|grep -qE '^(-d|-l)$' || usage
echo $baseHdfsPath|grep -qE '^/' || usage

if [[ $optionParam == "-l" ]]
then
	echo --------------------$startTime----------------------
	listDir "$baseHdfsPath"
	echo --------------------`date +'%F %T'`----------------------
else
	echo --------------------$startTime----------------------
	downLoadFiles "$baseHdfsPath"
	echo --------------------`date +'%F %T'`----------------------
fi

可是若是你的参数选项不少,好比 rsync、wget 等动辄几十上百的参数选项,那就必须用专业的工具来处理了,在 bash/shell 中咱们通常用:getopts/getopt  shell

一、bash 内置的 getopts:

先看简单的例子: bash

#!/bin/bash
while getopts 'd:Dm:f:t:' OPT; do
    case $OPT in
        d)
            DEL_DAYS="$OPTARG";;
        D)
            DEL_ORIGINAL='yes';;
        f)
            DIR_FROM="$OPTARG";;
        m)
            MAILDIR_NAME="$OPTARG";;
        t)
            DIR_TO="$OPTARG";;
        ?)
            echo "Usage: `basename $0` [options] filename"
    esac
done

shift $(($OPTIND - 1))

getopts后面的字符串就是可使用的选项列表,每一个字母表明一个选项,后面带:的意味着选项除了定义自己以外,还会带上一个参数做为选项的值,好比d:在实际的使用中就会对应-d 30,选项的值就是30;getopts字符串中没有跟随:的是开关型选项,不须要再指定值,至关于true/false,只要带了这个参数就是true。若是命令行中包含了没有在getopts列表中的选项,会有警告信息,若是在整个getopts字符串前面也加上个:,就能消除警告信息了。 工具

使用getopts识别出各个选项以后,就能够配合case来进行相应的操做了。操做中有两个相对固定的“常量”,一个是OPTARG,用来取当前选项的值,另一个是OPTIND,表明当前选项在参数列表中的位移。注意case中的最后一个选择──?,表明这若是出现了不认识的选项,所进行的操做。

选项参数识别完成以后,若是要取剩余的其它命令行参数,可使用shift把选项参数抹去,就像例子里面的那样,对整个参数列表进行左移操做,最左边的参数就丢失了(已经用case判断并进行了处理,再也不须要了),位移的长度正好是刚才case循环完毕以后的OPTIND - 1,由于参数从1开始编号,选项处理完毕以后,正好指向剩余其它参数的第一个。在这里还要知道,getopts在处理参数的时候,处理一个开关型选项,OPTIND加1,处理一个带值的选项参数,OPTIND则会加2。

最后,真正须要处理的参数就是$1~$#了,能够用for循环依次处理。

使用getopts处理参数虽然是方便,但仍然有两个小小的局限:

1.选项参数的格式必须是-d val,而不能是中间没有空格的-dval。
2.全部选项参数必须写在其它参数的前面,由于getopts是从命令行前面开始处理,遇到非-开头的参数,或者选项参数结束标记--就停止了,若是中间遇到非选项的命令行参数,后面的选项参数就都取不到了。
3.不支持长选项, 也就是--debug之类的选项

再看个实例: ui

#!/bin/bash
echo 初始 OPTIND: $OPTIND

while getopts "a:b:c" arg #选项后面的冒号表示该选项须要参数
do
    case $arg in
        a)
			echo "a's arg:$OPTARG" #参数存在$OPTARG中
			;;
        b)
			echo "b's arg:$OPTARG"
			;;
        c)
			echo "c's arg:$OPTARG"
			;;
        ?)  #当有不认识的选项的时候arg为?
			echo "unkonw argument"
			exit 1
		;;
    esac
done

echo 处理完参数后的 OPTIND:$OPTIND
echo 移除已处理参数个数:$((OPTIND-1))
shift $((OPTIND-1))
echo 参数索引位置:$OPTIND
echo 准备处理余下的参数:
echo "Other Params: $@"
结果:
june@Win7 192.168.1.111 02:32:45 ~ >
bash b.sh -a 1 -b 2 -c 3  test -oo xx -test
初始 OPTIND: 1
a's arg:1
b's arg:2
c's arg:
处理完参数后的 OPTIND:6
移除已处理参数个数:5
参数索引位置:6
准备处理余下的参数:
Other Params: 3 test -oo xx -test
june@Win7 192.168.1.111 02:32:49 ~ >
bash b.sh -a 1 -c 3 -b 2 test -oo xx -test   # 非参数选项注意顺序与值,不要多传
初始 OPTIND: 1
a's arg:1
c's arg:
处理完参数后的 OPTIND:4
移除已处理参数个数:3
参数索引位置:4
准备处理余下的参数:
Other Params: 3 -b 2 test -oo xx -test
june@Win7 192.168.1.111 02:33:14 ~ >
bash b.sh -a 1 -c -b 2 test -oo xx -test
初始 OPTIND: 1
a's arg:1
c's arg:
b's arg:2
处理完参数后的 OPTIND:6
移除已处理参数个数:5
参数索引位置:6
准备处理余下的参数:
Other Params: test -oo xx -test
june@Win7 192.168.1.111 02:33:22 ~ >

二、外部强大的参数解析工具:getopt

先来看下getopt/getopts的区别
1. getopts是bash内建命令的, 而getopt是外部命令
2. getopts不支持长选项, 好比: --date
3. 在使用getopt的时候, 每处理完一个位置参数后都须要本身shift来跳到下一个位置, getopts只须要在最后使用shift $(($OPTIND - 1))来跳到parameter的位置。
4. 使用getopt时, 在命令行输入的位置参数是什么, 在getopt中须要保持原样, 好比 -t , 在getopt的case语句中也要使用-t,  而getopts中不要前面的-。
5. getopt每每须要跟set配合使用
6. getopt -o的选项注意一下 spa

7. getopts 使用语法简单,getopt 使用语法较复杂 .net

8. getopts 不会重排全部参数的顺序,getopt 会重排参数顺序 命令行

9. getopts 出现的目的是为了代替 getopt 较快捷的执行参数分析工做 debug

下面是getopt自带的一个例子: unix

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->
#!/bin/bash

# A small example program for using the new getopt(1) program.
# This program will only work with bash(1)
# An similar program using the tcsh(1) script language can be found
# as parse.tcsh

# Example input and output (from the bash prompt):
# ./parse.bash -a par1 'another arg' --c-long 'wow!*\?' -cmore -b " very long "
# Option a
# Option c, no argument
# Option c, argument `more'
# Option b, argument ` very long '
# Remaining arguments:
# --> `par1'
# --> `another arg'
# --> `wow!*\?'

# Note that we use `"$@"' to let each command-line parameter expand to a
# separate word. The quotes around `$@' are essential!
# We need TEMP as the `eval set --' would nuke the return value of getopt.

#-o表示短选项,两个冒号表示该选项有一个可选参数,可选参数必须紧贴选项
#		如-carg 而不能是-c arg
#--long表示长选项
#"$@" :参数自己的列表,也不包括命令自己
# -n:出错时的信息
# -- :举一个例子比较好理解:
#咱们要建立一个名字为 "-f"的目录你会怎么办?
# mkdir -f #不成功,由于-f会被mkdir看成选项来解析,这时就可使用
# mkdir -- -f 这样-f就不会被做为选项。

TEMP=`getopt -o ab:c:: --long a-long,b-long:,c-long:: \
     -n 'example.bash' -- "$@"`

if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi

# Note the quotes around `$TEMP': they are essential!
#set 会从新排列参数的顺序,也就是改变$1,$2...$n的值,这些值在getopt中从新排列过了
eval set -- "$TEMP"

#通过getopt的处理,下面处理具体选项。

while true ; do
    case "$1" in
        -a|--a-long) echo "Option a" ; shift ;;
        -b|--b-long) echo "Option b, argument \`$2'" ; shift 2 ;;
        -c|--c-long)
            # c has an optional argument. As we are in quoted mode,
            # an empty parameter will be generated if its optional
            # argument is not found.
            case "$2" in
                "") echo "Option c, no argument"; shift 2 ;;
                *)  echo "Option c, argument \`$2'" ; shift 2 ;;
            esac ;;
        --) shift ; break ;;
        *) echo "Internal error!" ; exit 1 ;;
    esac
done
echo "Remaining arguments:"
for arg do
   echo '--> '"\`$arg'" ;
done
关于 getopt 选项重排的解释:

好比咱们使用
./test -a  -b arg arg1 -c 
你能够看到,命令行中多了个arg1参数,在通过getopt和set以后,命令行会变为:
-a -b arg -c -- arg1
$1指向-a,$2指向-b,$3指向arg,$4指向-c,$5指向--,而多出的arg1则被放到了最后。

getopt 对参数顺序进行重排的意义:这样能够将带 "-" 或 "–" 的参数写在其余参数的前面,也能够写在后面,而 getopts 是没有这样的能力的,具体没有的缘由就是由于 getopts 直接进入了 while 循环处理参数,而 getopt 游一个 set — ${ARGS} 的过程。另外还要注意到的是,在使用 getopt 处理完参数以后,"${@}" 变量 “被清洗干净了” ,里面包含了全部不带 "-" 或 "–" 的参数,因此你能够继续使用 ${1},${2} 等来调用他们。

三、Refer:

一、Bash Shell中命令行选项/参数处理

http://www.cnblogs.com/FrankTan/archive/2010/03/01/1634516.html

二、bash处理命令行参数:getopts/getopt 

http://blog.chinaunix.net/uid-21651880-id-3392466.html

三、getopt 使用教程并与 getopts 比较

http://hiaero.net/getopts-versus-getopt/

四、bash getopts, short options only, all require values, own validation

http://unix.stackexchange.com/questions/75219/bash-getopts-short-options-only-all-require-values-own-validation

相关文章
相关标签/搜索