`
jobar
  • 浏览: 340475 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Shell script中使用getopt例子

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

#!/bin/bash
set -- `getopt -q ab:c "$@"`
while [ -n "$1" ]
do
  case "$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
 shift
done
count=1
for 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/bash
while getopts :ab:c opt
do
 case $opt in
 a) echo "-a option";;
 b) echo "-b option with value $OPTARG";;
 c) echo "-c option";;
 *) echo $opt not a option;;
 esac
done

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/bash
while getopts :ab:cd opt
do
 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;;
 esac
done
count=1
shift $[$OPTIND-1]
for para in "$@"
do
echo "#$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
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics