Bash中陷阱的退出代码 [英] Exit code of traps in Bash
问题描述
这是 myscript.sh
:
#!/bin/bash
function mytrap {
echo "Trapped!"
}
trap mytrap EXIT
exit 3
当我运行它时:
> ./myscript.sh
echo $?
3
为什么脚本的退出代码带有陷阱的退出代码与没有陷阱的退出代码为何相同?通常,函数隐式返回最后执行的命令的退出代码.在这种情况下:
Why is the exit code of the script the exit code with the trap the same as without it? Usually, a function returns implicitly the exit code of the last command executed. In this case:
- echo返回0
- 我希望
mytrap
返回0 - 由于
mytrap
是最后执行的函数,因此脚本应返回0
- echo returns 0
- I would expect
mytrap
to return 0 - Since
mytrap
is the last function executed, the script should return 0
为什么不是这种情况?我的想法哪里错了?
Why is this not the case? Where is my thinking wrong?
推荐答案
从下面的 man bash
页面中查找参考,
Look the reference from the below man bash
page,
退出[n]使外壳退出,状态为n.如果省略n,则退出状态为最后执行的命令的退出状态.在外壳终止之前 执行 EXIT 上的陷阱.
您拥有脚本的调试版本,以证明这一点,
You have the debug version of the script to prove that,
+ trap mytrap EXIT
+ exit 3
+ mytrap
+ echo 'Trapped!'
Trapped!
考虑与您在注释中提到的相同, trap
函数返回错误代码
Consider the same as you mentioned in your comments, the trap
function returning an error code,
function mytrap {
echo "Trapped!"
exit 1
}
查看脚本的扩展版本,
+ trap mytrap EXIT
+ exit 3
+ mytrap
+ echo 'Trapped!'
Trapped!
+ exit 1
和
echo $?
1
要捕获 trap
函数上的退出代码,
To capture the exit code on trap
function,
function mytrap {
echo "$?"
echo "Trapped!"
}
这篇关于Bash中陷阱的退出代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!