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

bra*_*ito 47 bash message exit

是否可以使用消息退出错误,而不使用if语句?

[[ $TRESHOLD =~ ^[0-9]+$ ]] || exit ERRCODE "Threshold must be an integer value!"
Run Code Online (Sandbox Code Playgroud)

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

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

编辑

我知道这会有效,但如何numeric arg required在我的自定义消息后抑制显示?

[[ $TRESHOLD =~ ^[0-9]+$ ]] || exit "Threshold must be an integer value!"
Run Code Online (Sandbox Code Playgroud)

P.P*_*.P. 54

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

    [[ $TRESHOLD =~ ^[0-9]+$ ]] || \
     { echo "Threshold must be an integer value!"; exit $ERRCODE; }
Run Code Online (Sandbox Code Playgroud)

  • “TRESHOLD”可能是空的。`echo` 转到标准输出。所以重定向2将不起作用。您可以打印到 stderr: `[[ $TRESHOLD =~ ^[0-9]+$ ]] || { echo 1>&2 "阈值必须是整数值!"; 退出$ERRCODE;}` (2认同)
  • `exit`只接受一个选项*integer*(退出代码).所以传递像"消息"这样的字符串`将无效. (2认同)
  • 哦是的。我很愚蠢,我很困惑,因为打印我的自定义消息是该错误的副作用。 (2认同)

kon*_*box 24

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

function fail {
    printf '%s\n' "$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]+$ ]] || fail "Threshold must be an integer value!"
Run Code Online (Sandbox Code Playgroud)


noo*_*nex 7

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

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