用 bash 中的错误消息退出(在线)

是否可能在出现错误时退出,并使用 如果语句显示一条消息 没有

[[ $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!"
88387 次浏览

exit doesn't take more than one argument. To print any message like you want, you can use echo and then exit.

    [[ $TRESHOLD =~ ^[0-9]+$ ]] || \
{ echo "Threshold must be an integer value!"; exit $ERRCODE; }

You can use a helper function:

function fail {
printf '%s\n' "$1" >&2 ## Send message to stderr.
exit "${2-1}" ## Return a code specified by $2, or 1 by default.
}


[[ $TRESHOLD =~ ^[0-9]+$ ]] || fail "Threshold must be an integer value!"

Function name can be different.

Using exit directly may be tricky as the script may be sourced from other places. I prefer instead using subshell with set -e (plus errors should go into cerr, not cout) :

set -e
[[ $TRESHOLD =~ ^[0-9]+$ ]] || \
(>&2 echo "Threshold must be an integer value!"; exit $ERRCODE)

how about just echo a text and then exit:

echo "No Such File" && exit