是否可以使用消息退出错误,而不使用if语句?
[[ $TRESHOLD =~ ^[0-9]+$ ]] || exit ERRCODE "Threshold must be an integer value!"
当然||
的右侧不起作用,只是为了让你更好地了解我想要完成的事情。
实际上,我甚至不介意它将退出哪个ERR代码,只是为了显示消息。
编辑
我知道这会有效,但是如何在我的自定义消息后抑制numeric arg required
显示?
[[ $TRESHOLD =~ ^[0-9]+$ ]] || exit "Threshold must be an integer value!"
exit
不会有多个论点。要打印任何您想要的消息,您可以使用echo
然后退出。
[[ $TRESHOLD =~ ^[0-9]+$ ]] || \
{ echo "Threshold must be an integer value!"; exit $ERRCODE; }
为方便起见,您可以使用一个功能:
function error_exit {
echo "$1" >&2 ## Send message to stderr. Exclude >&2 if you don't want it that way.
exit "${2:-1}" ## Return a code specified by $2 or 1 by default.
}
[[ $TRESHOLD =~ ^[0-9]+$ ]] || error_exit "Threshold must be an integer value!"
直接使用exit
可能会很棘手,因为脚本可能来自其他地方。我更喜欢使用带有set -e
的子shell(加上错误应该进入cerr,而不是cout):
set -e
[[ $TRESHOLD =~ ^[0-9]+$ ]] || \
(>&2 echo "Threshold must be an integer value!"; exit $ERRCODE)