如何在Bash脚本退出之前运行命令?

编程入门 行业动态 更新时间:2024-10-12 14:19:48
本文介绍了如何在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脚本退出之前运行命令?

本文发布于:2023-11-23 19:09:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1622564.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:脚本   命令   如何在   Bash

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!