gpt4 book ai didi

bash - Bash脚本: How to ensure script exits on any error in function called with an “or” (||) condition?

转载 作者:行者123 更新时间:2023-12-03 07:52:45 25 4
gpt4 key购买 nike

这是一个示例脚本:

#!/bin/bash
set -euo pipefail

function_test () {
echo "Everything still ok."
thisdoesnotexist
echo "It continues running..."
}

function_test || { echo "Error occured in function_test."; exit 1; }

我希望此脚本在“thisdoesnotexist”上退出,因为set -e已激活。错误消息“在function_test中发生错误”。应该出现,或者至少应该退出脚本。相反,脚本继续运行:
$ ./testscript.sh 
Everything still ok.
./testscript.sh: Zeile 6: thisdoesnotexist: Kommando nicht gefunden.
It continues running...

我认为这是因为根据 set的手册,我在“或”(||)上下文中使用该函数:

Exit immediately [...] unless the command that fails is part of an until or while loop, part of an if statement, part of a && or || list, [...]



在脚本中处理此问题的最佳方法是什么?我删除了“||”并使用了这样的错误陷阱:
#!/bin/bash
set -Eeuo pipefail

errorhandler () {
echo "Errorhandler called. Exiting."
exit 1
}

trap "errorhandler" ERR

function_test () {
echo "Everything still ok."
thisdoesnotexist
echo "It continues running..."
}

function_test

哪个有效:
$ ./testscript.sh 
Everything still ok.
./testscript.sh: Zeile 13: thisdoesnotexist: Kommando nicht gefunden.
Errorhandler called. Exiting.

在这种情况下,尽管似乎无法输出用户友好的消息(例如,该消息包含脚本中发生错误的步骤)。为此,我至少必须将函数名称传递给错误陷阱。我尝试过,但是没有找到有效的解决方案。

您有更好的建议吗?

最佳答案

如果您想在出现错误的情况下做一些事情,并且知道某些地方可能出了问题,那么:

function_test () {
echo "Everything still ok."
thisdoesnotexist || {
# handle thisdoesnotexist failure
Echo "thisdoesnotexist failed" >&2
exit 1
}
echo "It continues running..."
if ! thisdoesnotexisteither; then
# Handle fail for thisdoesnotexisteither
Echo "thisdoesnotexisteither failed" >&2
exit 1
fi
}

现在,为了测试Bash中的错误处理,您可以使用此智能错误处理功能:
#!/usr/bin/env bash

# Generate an error
# @Params
# $1: Numeric error return code
# ${2[@]}: Messages
# @Output
# &1: Generic success message
# &2: Generic or passed error messages
# @Return
# $?: Intended return code
erroring() {
local rc=1
if [ "$#" -gt 0 ]; then
rc="$1"
shift
if printf '%d' "$rc" >/dev/null 2>&1; then
# rc is an integer
if [ "$rc" -gt 0 ]; then
printf $"Intended failure with code: %d\\n" "$rc" >&2
if [ "$#" -gt 0 ]; then
# There are supplied messages to print"
printf $"%d messages:\\n" "$#" >&2
printf '%q\n' "$@" >&2
fi
else
echo $"Intended success"
fi
else
printf $"Invalid non-numeric return code parameter: %q\\n" "$rc" >&2
rc=7
fi
else
erroring "$rc"
fi
return "$rc"
}

关于bash - Bash脚本: How to ensure script exits on any error in function called with an “or” (||) condition?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57446430/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com