jobar 发表于 2013-2-4 12:51:58

Shell script中使用getopt例子

使用getopt可以非常方便的格式话选项跟对应的参数,例子如下

#!/bin/bashset -- `getopt -q ab:c "$@"`while [ -n "$1" ]docase "$1" in-a)   echo "option -a";;-b) value="$2"echo "option -b with para $value"shift;;-c) echo "option -c";;--) shift      break;;*) echo "$1 not option";; esac shiftdonecount=1for para in "$@"do echo "#$count=$para" count=$[$count+1]done
./test -ab test1 -cd test2 test3 test4
结果:option -a
option -b with para 'test1'
option -c
#1='test2'
#2='test3'
#3='test4'

getopt 用法:
getopt options optstring parameters

对于./test -ab test1 -cd "test2 test3" test4
这样的参数类型,getopt是无能为力的。这就需要getopts了

#!/bin/bashwhile getopts :ab:c optdo case $opt in a) echo "-a option";; b) echo "-b option with value $OPTARG";; c) echo "-c option";; *) echo $opt not a option;; esacdone
OPTARG 环境变量存放对应选项的参数
./test -ab "hello,world" -cdefg
结果:
-a option
-b option with value hello,world
-c option
? not a option
? not a option
? not a option
? not a option

命令参数的处理
#!/bin/bashwhile getopts :ab:cd optdo case $opt in a) echo "-a option";; b) echo "-b option with value $OPTARG";; c) echo "-c option";; d) echo "-d option";; *) echo $opt not a option;; esacdonecount=1shift $[$OPTIND-1]for para in "$@"doecho "#$count=$para"count=$[$count+1] done
./test -abtest1 -cd test2 test3 test4
结果:
-a option
-b option with value test1
-c option
-d option
#1=test2
#2=test3
#3=test4
OPTIND环境变量存放getopts命令剩余的参数列表当前位值
用法:getopts optstring variable
页: [1]
查看完整版本: Shell script中使用getopt例子