【问题标题】:Order of getopts when no argument is passed to option没有参数传递给选项时的 getopts 顺序
【发布时间】:2019-03-04 13:28:33
【问题描述】:

我的问题是,当我使用脚本下面的 sn-ps 时,当我没有为选项提供参数时,会阻塞命令。如果我确实包含参数,一切都很好,我可以按任何顺序输入选项。

如何确保使用 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 "$1" ] || [ "$1" = "-" ] || [ "$1" = "--" ]
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 根本不支持选项的可选参数。 -f 之后的下一个参数将作为其参数,无论它是否也匹配另一个选项。

标签: bash command-line-arguments getopts


【解决方案1】:

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

您可以在您的案例陈述之前对参数进行错误检查吗?如下所示,但您可能会跳过有效参数,例如负数。

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} 需要一个参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-12
    • 1970-01-01
    • 2012-07-16
    • 2020-02-01
    • 1970-01-01
    • 2022-01-03
    相关资源
    最近更新 更多