在“陷阱退出"窗口中获取shell脚本的退出代码. [英] Get the exitcode of the shell script in a "trap EXIT"
问题描述
我想在我的Bash脚本中执行清理操作,如下所示:
I want to have a cleanup action in my Bash scripts, like this:
#! /bin/bash
set -eu
trap 'echo "E: failed with exitcode $?" 1>&2' ERR
true
false
使用 $?
是自然的选择,但事实并非如此.它始终包含 0
.我有什么办法可以监视" ERR
陷阱中的退出代码?
Using $?
came to mind as a natural choice, but this isn't the case. It always contains 0
. Is there any way that I can "spy" on the exitcode in the ERR
trap?
[更新:] 我不知道以前测试过什么.这段代码的工作原理很吸引人,因此我将其作为一个小巧的示例留在这里.
[Update:] I have no idea what I had tested before. This code works like a charm, so I'm leaving it here as a small and good example.
推荐答案
您的(可能是简化的)示例没有出现您提到的问题:
Your (probably simplified) example doesn't exhibit the problem you've mentioned:
+ 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
的命令,或者要遵守下面的代码段.引用手册:
Chances are that the command returning ERR
is executed in a &&
or ||
, or subject to other conditions mentioned in the snippet below. Quoting from the manual:
如果 sigspec 是
ERR
,则只要简单该命令的退出状态为非零,但必须遵守以下规定使适应.如果失败的命令是一部分,则不会执行ERR
陷阱在until
或while
关键字之后的命令列表中,在if
或elif
保留字之后的测试部分,在&&
或||
列表中执行的命令,或者该命令的返回状态正在使用!
反转.这些是相同的条件,errexit
选项.
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. TheERR
trap is not executed if the failed command is part of the command list immediately following anuntil
orwhile
keyword, part of the test following theif
orelif
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 theerrexit
option.
例如,如果您具有以下内容:
So if you have, for example, the following:
#! /bin/bash
set -eu
trap 'echo "E: failed with exitcode $?" 1>&2' ERR
false && true
执行该操作不会导致失败被困:
Executed it wouldn't cause the failure to be trapped:
+ set -eu
+ trap 'echo "E: failed with exitcode $?" 1>&2' ERR
+ false
这篇关于在“陷阱退出"窗口中获取shell脚本的退出代码.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!