没有参数传递给选项时的 getopts 顺序

Order of getopts when no argument is passed to option

我的问题是,当我使用下面的代码片段时,如果我没有为选项提供参数,脚本会阻塞订单。如果我包含参数,一切都很好,我可以按任何顺序输入选项。

如何确保使用 getopts 将不同的选项(-s 和 -f)正确映射到它们的变量?

请看下面的例子。

./script.bash -ftestfile -s0

search flag: 0
file: testfile

./script.bash -s0 -ftestfile

search flag: 0
file: testfile

到目前为止一切顺利..

当 f 选项不带参数(示例中的 testfile)时会出现此问题。 getopts 似乎不再能够识别 -s 应该是 inputsearch 而 -f 仍然是 inputfile。

./script.bash -f -s0

search flag: 
file: -s0

下面的魔法

s=0
while getopts :s:f:ih option
do
case "${option}" in
        s) inputsearch=${OPTARG};;
        f) inputfile=${OPTARG};;
        h) display_help; exit 1;;
        ?) display_help; exit 1;;
esac
done

# crap validation (must contain some option and option cant simply be "-" or "--"
if [ -z "" ] || [ "" = "-" ] || [ "" = "--" ]
then
        display_help
        exit 1
fi

#this fails
if [[ $inputsearch -gt 1 ]] || [[ -z $inputfile ]]
then
        display_help
        exit 1
else
        echo "search flag: $inputsearch"
        echo "file: $inputfile"
fi

感谢您的意见!

抱歉地说,简单的 getopts 就是这样。如果它需要一个参数,它只需要下一个单词作为参数。如果没有更多的参数,你只会得到一个错误。

您可以在 case 语句之前对参数进行错误检查吗?类似于下面的内容,但您可能会跳过有效参数,例如负数。

do
  if [ "${OPTARG:0:1}" == "-" ] 
  then 
    echo ERROR: argument ${OPTARG} to -${option} looks like an option
    exit 1
  fi

  case "${option}" in

您可以轻松地添加更多错误检查 ${OPTARG:1:1} 实际上在您的选项字符串中,也许 ${option} 需要一个参数。