-6ren">
gpt4 book ai didi

bash - Bash中陷阱的退出代码

转载 作者:行者123 更新时间:2023-11-29 08:53:21 27 4
gpt4 key购买 nike

这是myscript.sh:

#!/bin/bash

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

exit 3

当我运行它时:

> ./myscript.sh
echo $?
3

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

  1. echo 返回 0
  2. 我希望 mytrap 返回 0
  3. 因为 mytrap 是最后执行的函数,脚本应该返回 0

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

最佳答案

从下面的 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!"
}

关于bash - Bash中陷阱的退出代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41619629/

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