加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

bash – 在“陷阱EXIT”中获取shell脚本的exitcode

发布时间:2020-12-15 22:49:46 所属栏目:安全 来源:网络整理
导读:我想在我的 Bash脚本中进行清理操作,如下所示: #! /bin/bashset -eutrap 'echo "E: failed with exitcode $?" 12' ERRtruefalse 使用$?脑海中浮现出一种自然的选择,但事实并非如此.它总是包含0.有没有什么方法可以“侦察”ERR陷阱中的exitcode? [更新:]
我想在我的 Bash脚本中进行清理操作,如下所示:

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

true
false

使用$?脑海中浮现出一种自然的选择,但事实并非如此.它总是包含0.有没有什么方法可以“侦察”ERR陷阱中的exitcode?

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

解决方法

您的(可能是简化的)示例没有显示您提到的问题:

+ 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读