Tom*_*ger 13 bash shell case getopt
我正在使用getopt(不getops)为我的bash脚本提供处理选项和开关(long -option和short -o表单)的能力.
我希望能够捕获无效选项并处理它们,通常会回应用户应该尝试cmd --help然后退出脚本.
事实是,getopt捕获了无效选项,它本身输出一条消息,例如"getopt:invalid option - 'x'"
这是我用来设置我的getopt参数的模式:
set -- $(getopt -o $SHORT_OPTIONS -l $LONG_OPTIONS -- "$@")
Run Code Online (Sandbox Code Playgroud)
$ 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
Run Code Online (Sandbox Code Playgroud)
getopt -q将抑制输出,但我在case语句中的陷阱方案仍然无法达到我的预期.相反,程序只是执行,尽管参数无效.
l0b*_*0b0 10
这种风格适合我:
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
Run Code Online (Sandbox Code Playgroud)