我使用getopt (而不是getops)为我的bash脚本提供处理选项和开关(长--选项和短-o表单)的能力。
我希望能够捕获无效选项并处理它们,通常是回显用户应该尝试cmd --help,然后退出脚本。
问题是,无效的选项会被getopt捕获,它本身会输出一条消息,比如"getopt: invalid option -- 'x'“
下面是我用来设置getopt参数的模式:
set -- $(getopt -o $SHORT_OPTIONS -l $LONG_OPTIONS -- "$@")其中$LONG_OPTIONS和$SHORT_OPTIONS都是逗号分隔的选项列表。
下面是我处理选项的方式:
while [ $# -gt 0 ]
do
case "$1" in
-h|--help)
cat <<END_HELP_OUTPUT
Help
----
Usage: ./cmd.sh
END_HELP_OUTPUT
shift;
exit
;;
--opt1)
FLAG1=true
shift
;;
--opt2)
FLAG2=true
shift
;;
--)
shift
break
;;
*)
echo "Option $1 is not a valid option."
echo "Try './cmd.sh --help for more information."
shift
exit
;;
esac
donegetopt -q将禁止输出,但是我在case语句中的陷阱方案仍然无法完成我所期望的工作。相反,尽管存在无效参数,程序仍会执行。
发布于 2011-10-06 21:56:08
This风格适合我:
params="$(getopt -o d:h -l diff:,help --name "$cmdname" -- "$@")"
if [ $? -ne 0 ]
then
usage
fi
eval set -- "$params"
unset params
while true
do
case $1 in
-d|--diff)
diff_exec=(${2-})
shift 2
;;
-h|--help)
usage
exit
;;
--)
shift
break
;;
*)
usage
;;
esac
done发布于 2012-06-07 03:53:57
这不是最健壮的解决方案,但它是合理的;它依赖于以下几点:
getopt打印的错误消息以"getopt:“作为前缀。getopt错误消息是可以接受的,并增加了自定义信息。代码片段:
# Invoke getopt; suppress its stderr initially.
args=$(getopt -o $SHORT_OPTIONS -l $LONG_OPTIONS -- "$@" 2>/dev/null)
if [[ $? -ne 0 ]]; then # getopt reported failure
# Rerun the same getopt command so we can capture stderr output *only* this time.
# Inefficient (and a potential maintenance headache, if literals were involved), but this will only execute in case of invalid input.
# Alternatively, redirect the first getopt invocation's stderr output to a temp. file and read it here.
errmsg=$(getopt -o $SHORT_OPTIONS -l $LONG_OPTIONS -- "$@" 2>&1 1>&-)
# Strip getopt's prefix and augment with custom information.
echo -e "${errmsg#getopt: }\nTry './cmd.sh --help for more information." 1>&2
exit 1
fi发布于 2013-03-30 19:19:25
你一定要使用getopt吗?如果您只是使用
while [ $# -gt 0 ]; do
case "$1" in
-d|--diff)
diff_exec=(${2-})
shift
;;
-h|--help)
usage
exit
;;
--)
break
;;
*)
usage
;;
esac
shift
done然后,您自己的代码将执行检查。
https://stackoverflow.com/questions/7663481
复制相似问题