Bash getopts无法识别参数

时间:2012-09-12 19:23:27

标签: bash shell

while getopts ":hufc:p:i" opt; do

  case $opt in
    h)
        usage
        exit 1
        ;;
    u)
      DOUPDATE=false
      ;;
    f)
      DOCONFIRMATION=false
      ;;
    c)
       CUSTOMERTYPE=$OPTARG
       ;;
    p)
       CUSTOMERPROFILE=$OPTARG
       ;;
    i)
        echo "LOL $INSTALL"
        INSTALL=true
        ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      exit 1
      ;;
     :)
      echo "Option -$OPTARG requires an argument." >&2
      exit 1
      ;;
  esac
done

以上是我的bash代码。当我尝试在命令行中使用“i”作为参数时,不输入大小写。

我该怎么办?

1 个答案:

答案 0 :(得分:0)

如果您的命令行在i之前有任何无效选项,它将不会解析比错误更远的任何选项。如果您的命令行具有-c或-p而没有后续参数进入CustomerType或CustomerProfile,则它将不会进一步解析。

#Examples that should work
script.sh -i
script.sh -c customerX -p profileX -i
script.sh -iz

#Examples that will not work
script.sh -hi   #-h option will exit before it parses -i
script.sh -zi   #invalid option z will exit
script.sh -c customerX -p -i #Missing required argument after -p