自己做的以“-a” 参数为例子:
bash-3.00# ./getopts.sh -a
1 means your input is a
bash-3.00# ./getopts.sh -b
1 means your input is b
bash-3.00# ./getopts.sh -c
./getopts.sh: illegal option -- c
Usage: ./getopts.sh: [-a] [-b value] args
脚本内容:
bash-3.00# cat getopts.sh
#!/bin/sh
while getopts ab name
do
case $name in
a) aflag=1;echo $aflag means your input is "a";;
b) bflag=1
echo $bflag means your input is "b";;
?) printf "Usage: %s: [-a] [-b value] args\n" $0
exit 2;;
esac
done
bash-3.00# ./getopts.sh -a -c 10
1 means your input is a
this mean the value of $OPTARG is 10
bash-3.00# cat getopts.sh
#!/bin/sh
while getopts :abc: name
do
case $name in
a) aflag=1;echo $aflag means your input is "a"
;;
b) bflag=1
echo $bflag means your input is "b"
;;
c) echo this mean the value of '$OPTARG' is $OPTARG
;;
?) printf "Usage: %s: [-a] [-b value] args\n" $0
exit 2;;
esac
done
getopts后面用到两个:,第一个屏蔽系统报错,第二个要求c选项必须取值。
bash-3.00# ./getopts.sh -b bbbbbb -c cccccc
1 means your input is b
the value of $OPTARG is bbbbbb
2 means your option is now c
this mean the value of $OPTARG is cccccc
bash-3.00# cat getopts.sh
#!/bin/sh
while getopts :ab:c: name
do
case $name in
a) aflag=1;echo $aflag means your input is "a"
;;
b) bflag=1
echo $bflag means your input is "b"
echo the value of '$OPTARG' is $OPTARG;
;;
c) echo 2 means your option is now c
echo this mean the value of '$OPTARG' is $OPTARG
;;
?) printf "Usage: %s: [-a] [-b value] args\n" $0
exit 2;;
esac
done
$OPTARG的选项值随着选项的变化而变化。
阅读(1516) | 评论(1) | 转发(0) |