创建bash中的临时文件 [英] Creating temporary files in bash

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

问题描述

是否有客观更好的办法在bash脚本来创建临时文件?

Are there objectively better ways to create temporary files in bash scripts?

我通常只是他们的名字无论在我脑海中,如临时文件-123,因为当脚本结束将被删除。是否有比当前文件夹中覆盖可能的临时文件-123这样做以外的任何缺点?或者是有什么优势以更加谨慎的方式创建一个临时文件?

I normally just name them whatever comes to my mind, such as tempfile-123, since it will be deleted when the script is over. Is there any disadvantage in doing this other than overwriting a possible tempfile-123 in current folder? Or is there any advantage in creating a temporary file in a more careful way?

推荐答案

mktemp的(1)手册页解释了它相当不错:

The mktemp(1) man page explains it fairly well:

传统上,许多shell脚本走程序与名称
  该PID作为后缀,并把它作为临时文件名。这种
  命名方案是predictable,它创造比赛条件
  易攻击者获胜。一个更安全,但仍逊色,方法
  是使用相同的命名方案,使一个临时目录。而
  这样做允许一个以保证一个临时文件将不
  颠覆,它仍然允许服务攻击的简单否定。对于
  这些原因,认为mktemp的替代使用。

Traditionally, many shell scripts take the name of the program with the pid as a suffix and use that as a temporary file name. This kind of naming scheme is predictable and the race condition it creates is easy for an attacker to win. A safer, though still inferior, approach is to make a temporary directory using the same naming scheme. While this does allow one to guarantee that a temporary file will not be subverted, it still allows a simple denial of service attack. For these reasons it is suggested that mktemp be used instead.

我通常mktemp的调用的是一样的东西。

My usual invocation of mktemp is something like

mydir=$(mktemp -dt "$0")

这将创建一个临时目录,我可以在工作,并在其中我可以放心地命名的实际文件可读的东西和有用的。

which creates a temporary directory I can work in, and in which I can safely name the actual files something readable and useful.

编辑: mktemp的不达标,但它确实在很多平台上存在。上面的命令将产生在OS X上的目录,但是无法在GNU的coreutils'mktemp的,在这里你需要指定preFIX与* X * S,如 mktemp的-dt$ 0.XXXXXXXXXX 。 (帽尖,ceving)

mktemp is not standard, but it does exist on many platforms. The above command will generate a directory on OS X, but will fail on GNU coreutils' mktemp, where you need to specify the prefix with *X*s, like mktemp -dt "$0.XXXXXXXXXX". (Hat tip, ceving)

顺便说一句,安全创建临时文件是不仅仅是shell脚本更重要。这就是为什么Python有临时文件,Perl已经的File::Temp ,红宝石具有的将它视为,等等...

By the way, safe creation of temporary files is important for more than just shell scripting. That's why python has tempfile, perl has File::Temp, ruby has Tempfile, etc…

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

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