&2' ERR tr-6ren">
gpt4 book ai didi

bash - 在 "trap EXIT"中获取 shell 脚本的退出代码

转载 作者:行者123 更新时间:2023-11-29 09:00:41 25 4
gpt4 key购买 nike

我想在我的 Bash 脚本中执行清理操作,如下所示:

#! /bin/bash
set -eu
trap 'echo "E: failed with exitcode $?" 1>&2' ERR

true
false

使用 $? 是自然而然的选择,但事实并非如此。它始终包含 0。有什么方法可以“监视”ERR 陷阱中的退出代码?

[更新:] 我不知道我之前测试过什么。这段代码就像一个魅力,所以我把它留在这里作为一个小而好的例子。

最佳答案

您的(可能已简化)示例没有出现您提到的问题:

+ set -eu
+ trap 'echo "E: failed with exitcode $?" 1>&2' ERR
+ true
+ false
++ echo 'E: failed with exitcode 1'
E: failed with exitcode 1

有可能返回 ERR 的命令是在 &&|| 中执行的,或者受以下代码段中提到的其他条件的影响.引用自 manual :

If a sigspec is ERR, the command arg is executed whenever a simple command has a non-zero exit status, subject to the following conditions. The ERR trap is not executed if the failed command is part of the command list immediately following an until or while keyword, part of the test following the if or elif reserved words, part of a command executed in a && or || list, or if the command’s return status is being inverted using !. These are the same conditions obeyed by the errexit option.

例如,如果您有以下情况:

#! /bin/bash
set -eu
trap 'echo "E: failed with exitcode $?" 1>&2' ERR

false && true

执行它不会导致失败被困:

+ set -eu
+ trap 'echo "E: failed with exitcode $?" 1>&2' ERR
+ false

关于bash - 在 "trap EXIT"中获取 shell 脚本的退出代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19091498/

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