【问题标题】:getopts is not sending my options to standard outgetopts 没有将我的选项发送到标准输出
【发布时间】:2016-06-06 04:20:29
【问题描述】:

我开始尝试使用 getopts,但遇到了一些错误。当我输入无效选项(例如 -A)时,程序输出不是它需要的。

#!/bin/bash

function usage() {
    echo "Usage: $0 -h [database host] -d [test database name]"
    exit 1
}

while getopts “:h:d:” opt; do
  case ${opt} in
    h)
      db_host=$OPTARG
      ;;
    d)
      test_db=$OPTARG
      ;;
    \?)
      echo "Invalid option: -$OPTARG" 1>&2
      usage
      exit 1
      ;;
    :)
      echo “Option -$OPTARG requires an argument.” 1>$2
      usage
      exit 1
      ;;
  esac
done
shift $((OPTIND-1))

if [ -z $db_host ] || [ -z $test_db ]; then
    usage
else
    echo "Your host is $db_host and your test database is $test_db."
fi

示例程序输出:

./opt.sh: illegal option -- A
Invalid option: -
Usage: ./opt.sh -h [database host] -d [test database name]

所以,基本上是两个问题:

1) 我想完全摆脱第一个错误消息。我想提供我自己的错误信息。 2)为什么我的脚本不产生“无效选项:-A”而不仅仅是“无效选项:-”

【问题讨论】:

    标签: linux bash getopts


    【解决方案1】:

    getopts 的选项参数周围的引号类型错误,它们是“花引号”而不是 ASCII 双引号。因此,: 不是选项的第一个字符,因此您不会收到静默错误报告。

    改成

    while getopts ':h:d:' opt; do
    

    【讨论】:

    • 不确定您对报价的意思。我的键盘上只有一个“双引号”键,与“单引号”键相同。这些更改不起作用。只是吐出“无效选项:-?”
    • 查看问题中的代码,getopts 的参数周围有花引号。看起来您使用了文字处理器,并且它进行了“智能引用”替换。
    • 实际上,当我查看我的脚本时,我注意到引号的问题。不知道那是怎么发生的——好眼力。引用解决了这个问题,因为“无声报道”由于引用错误而没有被关注。但是,我不需要在 case 语句中将 $OPTARG 更改为 $opt。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-03
    • 1970-01-01
    • 2015-02-19
    • 1970-01-01
    相关资源
    最近更新 更多