+ -
当前位置:首页 → 问答吧 → shell 中getopts的疑问

shell 中getopts的疑问

时间:2011-04-15

来源:互联网

getopts用于解析shell的命令行参数。
有如下代码:
  1. #!/bin/bash

  2. CMD_OPT="o:"
  3. while getopts "$CMD_OPT" C
  4. do
  5.     case $C in
  6.         o)
  7.             echo "ooooooooooooo"
  8.         ;;

  9.         \?)
  10.             echo "******************"
  11.             exit 1
  12.         ;;
  13.     esac
  14. done
复制代码
如果运行的时候,输入任何一个字符串(不是以-开头),为什么没有提示任何错误
#./test.sh  abcd

而如果是以-开头的,则会提示错误
#./test.sh -abcd
./test.sh: illegal option -- a
******************


这是不是getopts的BUG? 有没有办法可以检查这样的非法出入。

作者: whpu000625   发布时间: 2011-04-15

这个链接可以解答你的疑惑
http://bbs.chinaunix.net/thread-1823335-1-1.html

作者: chenbin200818   发布时间: 2011-04-15

你程序都没abcd这些选项,当然报illegal option -- a

作者: chaogooler8888   发布时间: 2011-04-15

回复 chaogooler8888


    我是说如果执行#./test.sh  abcd,为什么不报错

作者: whpu000625   发布时间: 2011-04-15

感觉使用getopts存在很多问题啊

作者: whpu000625   发布时间: 2011-04-15

试试  :o: 前面一个冒号,后面一个冒号

还有你好像也没有使用 -o 选项阿..

作者: 南极雨   发布时间: 2011-04-15