在意外的bash出口中删除创建的临时文件 [英] Removing created temp files in unexpected bash exit

查看:183
本文介绍了在意外的bash出口中删除创建的临时文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从bash脚本创建临时文件.我将在处理结束时删除它们,但是由于脚本运行了很长时间,因此,如果我在运行过程中将其杀死或仅按CTRL-C杀死,则不会删除临时文件.
有什么办法可以在执行结束之前捕获这些事件并清理文件?

I am creating temporary files from a bash script. I am deleting them at the end of the processing, but since the script is running for quite a long time, if I kill it or simply CTRL-C during the run, the temp files are not deleted.
Is there a way I can catch those events and clean-up the files before the execution ends?

此外,这些临时文件的命名和位置是否存在某种最佳实践?
我目前不确定使用之间:

Also, is there some kind of best practice for the naming and location of those temp files?
I'm currently not sure between using:

TMP1=`mktemp -p /tmp`
TMP2=`mktemp -p /tmp`
...

TMP1=/tmp/`basename $0`1.$$
TMP2=/tmp/`basename $0`2.$$
...

或者也许有一些更好的解决方案?

Or maybe is there some better solutions?

推荐答案

您可以设置"陷阱"在退出时执行,或在Control-C上执行以进行清理.

You could set a "trap" to execute on exit or on a control-c to clean up.

trap "{ rm -f $LOCKFILE; }" EXIT

或者,我最喜欢的unix-ism之一是打开一个文件,然后在您仍然打开它的同时将其删除.该文件保留在文件系统上,您可以对其进行读写,但是一旦程序退出,该文件就会消失.不过,不确定如何在bash中执行该操作.

Alternatively, one of my favourite unix-isms is to open a file, and then delete it while you still have it open. The file stays on the file system and you can read and write it, but as soon as your program exits, the file goes away. Not sure how you'd do that in bash, though.

BTW:我会推荐一个参数,而不是使用您自己的解决方案,而推荐使用mktemp:如果用户期望您的程序将要创建巨大的临时文件,则他可能希望将TMPDIR设置为更大的位置,例如/var/tmp. mktemp意识到,您的手动解决方案(第二个选项)没有.例如,我经常使用TMPDIR=/var/tmp gvim -d foo bar.

BTW: One argument I'll give in favour of mktemp instead of using your own solution: if the user anticipates your program is going to create huge temporary files, he might want set TMPDIR to somewhere bigger, like /var/tmp. mktemp recognizes that, your hand-rolled solution (second option) doesn't. I frequently use TMPDIR=/var/tmp gvim -d foo bar, for instance.

这篇关于在意外的bash出口中删除创建的临时文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆