shell getopts 参数收集问题
shell getopts parameters collection issue
我的 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 并忽略时区参数。我不确定我在这里做错了什么。它也没有显示帮助功能。有人可以帮忙吗。下面是调用脚本的语法。
./script_name.sh -g 20225 -t Europe/Zurich
./script_name.sh -g 20225 -t CEST
您的问题出在 optstring 上。您正在指定 h:
,这意味着 -h
需要一个选项。您还指定了没有 :
的 t
,这意味着 t
不需要选项。
让 g
和 t
接受选项而 h
不需要的 optstring 是 hg:t:
我的 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 并忽略时区参数。我不确定我在这里做错了什么。它也没有显示帮助功能。有人可以帮忙吗。下面是调用脚本的语法。
./script_name.sh -g 20225 -t Europe/Zurich
./script_name.sh -g 20225 -t CEST
您的问题出在 optstring 上。您正在指定 h:
,这意味着 -h
需要一个选项。您还指定了没有 :
的 t
,这意味着 t
不需要选项。
让 g
和 t
接受选项而 h
不需要的 optstring 是 hg:t: