在bash(oneline)中退出并显示错误消息

问题描述 投票:39回答:3

是否可以使用消息退出错误,而不使用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!"
bash message exit
3个回答
51
投票

exit不会有多个论点。要打印任何您想要的消息,您可以使用echo然后退出。

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

22
投票

为方便起见,您可以使用一个功能:

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!"

2
投票

直接使用exit可能会很棘手,因为脚本可能来自其他地方。我更喜欢使用带有set -e的子shell(加上错误应该进入cerr,而不是cout):

set -e
[[ $TRESHOLD =~ ^[0-9]+$ ]] || \
     (>&2 echo "Threshold must be an integer value!"; exit $ERRCODE)
© www.soinside.com 2019 - 2024. All rights reserved.