我正在使用getopt
(not getops
) 为我的 bash 脚本提供处理选项和开关(长 --option 和短 -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
done
getopt -q
将抑制输出,但我在语句中的捕获方案case
仍然无法达到我的预期。相反,程序只是执行,尽管参数无效。