本文介绍了如何在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脚本退出之前运行命令?
发布评论