如何在Bash脚本退出之前运行命令? [英] How to run a command before a Bash script exits?
本文介绍了如何在Bash脚本退出之前运行命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果Bash脚本具有set -e
,并且脚本中的命令返回错误,那么如何在脚本退出之前进行一些清除?
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?
例如:
#!/bin/bash
set -e
mkdir /tmp/foo
# ... do stuff ...
rm -r /tmp/foo
即使... do stuff ...
中的命令之一失败,我如何确保将/tmp/foo
删除?
How can I ensure that /tmp/foo
is removed, even if one of the commands in ... do stuff ...
fails?
推荐答案
以下是使用陷阱的示例:
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
输出:
dbrown@luxury:~ $ sh traptest
t: line 9: asdffdsa: command not found
Removing /tmp/foo
dbrown@luxury:~ $
请注意,即使asdffdsa行失败,清理仍会执行.
Notice that even though the asdffdsa line failed, the cleanup still was executed.
这篇关于如何在Bash脚本退出之前运行命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文