如何在 Bash 脚本退出之前运行命令?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2129923/
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 run a command before a Bash script exits?
提问by David Wolever
If a Bash script has set -e
, and a command in the script returns an error, how can I do some cleanup before the script exits?
如果 Bash 脚本有set -e
,并且脚本中的命令返回错误,我如何在脚本退出之前进行一些清理?
For example:
例如:
#!/bin/bash
set -e
mkdir /tmp/foo
# ... do stuff ...
rm -r /tmp/foo
How can I ensure that /tmp/foo
is removed, even if one of the commands in ... do stuff ...
fails?
/tmp/foo
即使其中一个命令... do stuff ...
失败,我如何确保删除它?
回答by devguydavid
Here's an example of using trap:
下面是一个使用陷阱的例子:
#!/bin/bash -e
function cleanup {
echo "Removing /tmp/foo"
rm -r /tmp/foo
}
trap cleanup EXIT
mkdir /tmp/foo
asdffdsa #Fails
Output:
输出:
dbrown@luxury:~ $ sh traptest
t: line 9: asdffdsa: command not found
Removing /tmp/foo
dbrown@luxury:~ $
Notice that even though the asdffdsa line failed, the cleanup still was executed.
请注意,即使 asdffdsa 行失败,仍会执行清理。
回答by dmckee --- ex-moderator kitten
From the bash
manpage (concerning builtins):
从bash
联机帮助页(关于内置函数):
trap [-lp] [[arg] sigspec ...]
The command arg is to be read and executed when the shell receives signal(s) sigspec.
trap [-lp] [[arg] sigspec ...]
当 shell 接收到信号 sigspec 时,将读取并执行命令 arg。
So, as indicated in Anon.'s answer, call trap
early in the script to set up the handler you desire on ERR.
因此,如Anon.'s answer 中所示,请trap
在脚本中尽早调用以在 ERR 上设置您想要的处理程序。
回答by Anon.
From the reference for set
:
从参考为set
:
-e
Exit immediately if a simple command (see section 3.2.1 Simple Commands) exits with a non-zero status, unless the command that fails is part of an until or while loop, part of an if statement, part of a && or || list, or if the command's return status is being inverted using !. A trap on ERR, if set, is executed before the shell exits.
-e
如果一个简单的命令(参见 3.2.1 简单命令)以非零状态退出,则立即退出,除非失败的命令是 until 或 while 循环的一部分、if 语句的一部分、&& 或 || 的一部分 列表,或者命令的返回状态是否正在使用 ! 反转。如果设置了 ERR 上的陷阱,则会在 shell 退出之前执行。
(Emphasis mine).
(强调我的)。
回答by Saftever
sh
version of devguydavid's answer.
sh
devguydavid 的回答版本。
#!/bin/sh
set -e
cleanup() {
echo "Removing /tmp/foo"
rm -r /tmp/foo
}
trap cleanup EXIT
mkdir /tmp/foo
asdffdsa #Fails
ref: shellscript.sh