以 bash 中的错误消息退出(oneline)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24597818/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 00:54:47  来源:igfitidea点击:

exit with error message in bash (oneline)

bashmessageexit

提问by branquito

Is it possible to exit on error, with a message, withoutusing ifstatements?

是否可以在使用if语句的情况下错误退出并显示消息?

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

Of course the right side of ||won't work, just to give you better idea of what I am trying to accomplish.

当然右侧的||不起作用,只是为了让您更好地了解我要完成的工作。

Actually, I don't even mind with which ERR code it's gonna exit, just to show the message.

实际上,我什至不介意它退出哪个 ERR 代码,只是为了显示消息。

EDIT

编辑

I know this will work, but how to suppress numeric arg requiredshowing after my custom message?

我知道这会起作用,但是如何numeric arg required在我的自定义消息之后抑制显示?

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

回答by P.P

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

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

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

回答by konsolebox

You can use a helper function:

您可以使用辅助函数:

function fail {
    printf '%s\n' "" >&2  ## Send message to stderr. Exclude >&2 if you don't want it that way.
    exit "${2-1}"  ## Return a code specified by  or 1 by default.
}

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

Function name can be different.

函数名称可以不同。

回答by noonex

Using exitdirectly 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) :

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

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