如何在 Bash 脚本中捕获退出代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5312266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to trap exit code in Bash script
提问by Dagang
There're many exit points in my bash code. I need to do some clean up work on exit, so I used trap to add a callback for exit like this:
我的 bash 代码中有很多退出点。我需要在退出时做一些清理工作,所以我使用 trap 为退出添加回调,如下所示:
trap "mycleanup" EXIT
The problem is there're different exit codes, I need to do corresponding cleanup works. Can I get exit code in mycleanup?
问题是有不同的退出代码,我需要做相应的清理工作。我可以在 mycleanup 中获得退出代码吗?
回答by bmk
I think you can use $?
to get the exit code.
我想你可以$?
用来获取退出代码。
回答by Paul Tobias
The accepted answer is basically correct, I just want to clarify things.
接受的答案基本上是正确的,我只是想澄清一些事情。
The following example works well:
以下示例运行良好:
#!/bin/bash
cleanup() {
rv=$?
rm -rf "$tmpdir"
exit $rv
}
tmpdir="$(mktemp)"
trap "cleanup" INT TERM EXIT
# Do things...
But you have to be more careful if doing cleanup inline, without a function. For example this won't work:
但是如果在没有函数的情况下进行内联清理,则必须更加小心。例如,这将不起作用:
trap "rv=$?; rm -rf $tmpdir; exit $rv" INT TERM EXIT
Instead you have to escape the $rv
and $?
variables:
相反,您必须转义$rv
和$?
变量:
trap "rv=$?; rm -rf $tmpdir; exit $rv" INT TERM EXIT
You might also want to escape $tmpdir
, as it will get evaluated when the trap line gets executed and if the tmpdir
value changes later that will not give you the expected behaviour.
您可能还想转义$tmpdir
,因为它会在陷阱行执行时进行评估,并且如果tmpdir
值稍后更改,则不会为您提供预期的行为。
Edit: Use shellcheckto check your bash scripts and be aware of problems like this.
编辑:使用shellcheck检查您的 bash 脚本并注意此类问题。
回答by anthony
I've found it is better to separate EXIT trap from the trap for other signals
我发现最好将 EXIT 陷阱与其他信号的陷阱分开
Example trap test script...
示例陷阱测试脚本...
umask 77
tmpfile=`tmpfile.$$`
trap 'rm -f "$tmpfile"' EXIT
trap 'exit 2' HUP INT QUIT TERM
touch $tmpfile
read -r input
exit 10
The temporary file is cleaned up. The file exit value of 10 is preserved! Interrupts result in an exit value of 2
临时文件被清理。文件退出值 10 被保留!中断导致退出值为 2
Basically as long as you don't use "exit" in a EXIT trap, it will exit with the original exit value preserved.
基本上只要您不在 EXIT 陷阱中使用“exit”,它就会退出并保留原始退出值。
ASIDE: Note the quoting in the EXIT trap. That lets me change what file needs to be cleaned up during the scripts lifetime. I often also include a test for the existence of the $tmpfile before trying to remove it, so I don't even need to set it at the start of the script, only before creating it.
旁白:注意 EXIT 陷阱中的引用。这让我可以更改在脚本生命周期内需要清理的文件。在尝试删除 $tmpfile 之前,我经常还包括一个测试它是否存在,所以我什至不需要在脚本的开头设置它,只需要在创建它之前。