用户使用 getopts 冒号功能指定的错误

问题描述 投票:0回答:1

我想要指定是使用

Normal Error Reporting
还是
Silent Error Reporting
getopts
一起提供的能力。

然后我就可以像这样调用我的 bash 函数

mari -s -n VAL -z VAL

-s
将设置静默错误报告(即设置
opstring=":n:z:"
),否则将使用正常错误报告(
opstring="n:z:"
)。

目前我在函数内部硬接线

opstring

mari() 
{

 impl=""
 if [[ "$impl"  == "SILENT" ]]; then
   opstring=":n:z:"  # Short options string
 else
   opstring="n:z:"
 fi

 while getopts "$opstring" opname; do
  case ${opname} in
    ("n")
      if [ -n "$OPTARG" ]; then
        echo "The string is not empty"
      else
        echo "The string is empty"
      fi
      ;;
    ("z")
      if [ -z "$OPTARG" ]; then
        echo "The string is empty"
      else
        echo "The string is not empty"
      fi
      ;;
    (?)
      ## Invalid Option Found, OPNAME set to '?'
      echo "Invalid option: -$OPTARG" 1>&2
      exit 1
      ;;
    (:)
      ## Required option argument not found, OPNAME set to ':'
      echo "Option -$OPTARG requires an argument" 1>&2
      exit 1
      ;;
  esac
 done
}
bash getopts
1个回答
0
投票

一旦遇到

s
就修改opstring。

?
是一个 glob,它匹配任何东西。你必须引用它。

mari() {
    local opstring
    opstring="sn:z:"
    while getopts "$opstring" opname; do
        case ${opname} in
        "s")
            opstring=":${opstring%%:}"
            ;;
        "n")
            if [ -n "$OPTARG" ]; then
                echo "The string is not empty"
            else
                echo "The string is empty"
            fi
            ;;
        "z")
            if [ -z "$OPTARG" ]; then
                echo "The string is empty"
            else
                echo "The string is not empty"
            fi
            ;;
        '?')
            ## Invalid Option Found, OPNAME set to '?'
            echo "Invalid option: -$OPTARG" 1>&2
            exit 1
            ;;
        ':')
            ## Required option argument not found, OPNAME set to ':'
            echo "Option -$OPTARG requires an argument" 1>&2
            exit 1
            ;;
        esac
    done
}

echo "no invalid option:"
mari -s -bla
echo "invalid option:"
mari -bla
© www.soinside.com 2019 - 2024. All rights reserved.