Bash 中陷阱的退出代码

Exit code of traps in Bash

这是myscript.sh:

#!/bin/bash

function mytrap {
    echo "Trapped!"
}
trap mytrap EXIT

exit 3

当我 运行 它时:

> ./myscript.sh
echo $?
3

为什么脚本的退出代码有trap和没有trap的退出代码是一样的?通常,函数 returns 隐含了最后执行的命令的退出代码。在这种情况下:

  1. 回声returns 0
  2. 我希望 mytrap 到 return 0
  3. 因为mytrap是最后执行的函数,脚本应该return0

为什么不是这样?我的想法哪里错了?

从下面的 man bash 页面查看参考资料,

exit [n] Cause the shell to exit with a status of n. If n is omitted, the exit status is that of the last command executed. A trap on EXIT is executed before the shell terminates.

你有脚本的调试版本来证明,

+ trap mytrap EXIT
+ exit 3
+ mytrap
+ echo 'Trapped!'
Trapped!

考虑与您在评论中提到的相同,trap 函数返回错误代码,

function mytrap {
    echo "Trapped!"
    exit 1
}

查看脚本的扩展版本,

+ trap mytrap EXIT
+ exit 3
+ mytrap
+ echo 'Trapped!'
Trapped!
+ exit 1

echo $?
1

要捕获 trap 函数的退出代码,

function mytrap {
    echo "$?"
    echo "Trapped!"
}