【问题标题】:shell getopts parameters collection issueshell getopts 参数收集问题
【发布时间】:2018-04-17 11:28:07
【问题描述】:

我的 shell 脚本中有以下代码。

show_help()
{
    cat <<EOF
Usage: ${0##*/} [-h help] [-g GATEWAY_HOSTID] [-t TIMEZONE]

         -h                     display this help and exit
         -g GATEWAY_HOSTID      zabbix gateway identifier (e.g. '20225')
         -t Time Zone          TimeZone against which you want to test
EOF
}

OPTIND=1

while getopts "g:h:t" opt; do
  case "$opt" in
    h)
      show_help
      exit 0
      ;;
    g)
      gateway_hostid=$OPTARG
      ;;
    t)
      timezone=$OPTARG
      ;;
    esac
done

shift $((OPTIND-1))

if [[ ! $timezone ]]; then
    timezone="UTC"
fi

if [[ ! $gateway_hostid ]]; then
    echo "hostid is missing!!! Exiting now."
    exit
fi

当我执行脚本时,它只需要参数 gateway_hostid 并忽略 timezone 参数。我不确定我在这里做错了什么。它也没有显示帮助功能。有人可以帮忙吗。下面是调用脚本的语法。

./script_name.sh -g 20225 -t Europe/Zurich
./script_name.sh -g 20225 -t CEST

【问题讨论】:

  • 您可能正在寻找getopts "g:ht:"

标签: linux bash shell getopts


【解决方案1】:

您的问题出在 optstring 上。您正在指定 h:,这意味着 -h 需要一个选项。您还指定了 t 没有 : 意味着 t 不期望选项。

拥有gt 选项和h 不需要一个选项的optstring 是hg:t:

【讨论】:

    猜你喜欢
    • 2016-11-27
    • 1970-01-01
    • 1970-01-01
    • 2019-06-18
    • 2019-09-30
    • 2018-08-14
    • 2011-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多