getopts 方便的做参数和参数选项处理

自己做的以“-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的选项值随着选项的变化而变化。

作者: haiwei_wu   发布时间: 2010-09-03