Chinaunix首页 | 论坛 | 博客
  • 博客访问: 279688
  • 博文数量: 107
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 74
  • 用 户 组: 普通用户
  • 注册时间: 2016-11-18 09:57
文章分类

全部博文(107)

文章存档

2023年(2)

2021年(1)

2017年(1)

2015年(4)

2014年(9)

2013年(4)

2012年(14)

2011年(49)

2010年(23)

分类: LINUX

2010-09-03 10:05:10

自己做的以“-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) |
给主人留下些什么吧!~~

chinaunix网友2010-09-05 14:56:56

Download More than 1000 free IT eBooks: http://free-ebooks.appspot.com