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

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

问题描述

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

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

我通常只为它们命名我想到的任何名称,例如 tempfile-123,因为它会在脚本结束时被删除.除了覆盖当前文件夹中可能的 tempfile-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 作为后缀并将其用作临时文件名.这类命名方案的数量是可预测的,它创建的竞争条件是进攻方很容易获胜.一种更安全但仍然较差的方法是使用相同的命名方案创建一个临时目录.尽管这确实允许人们保证临时文件不会被被颠覆,它仍然允许简单的拒绝服务攻击.为了这些原因建议改用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 之类的东西

In a script, I invoke mktemp something like

mydir=$(mktemp -d "${TMPDIR:-/tmp/}$(basename $0).XXXXXXXXXXXX")

它创建了一个我可以在其中工作的临时目录,我可以在其中安全地将实际文件命名为可读且有用的名称.

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

mktemp 不是标准的,但它确实存在于许多平台上.X"通常会转换为一些随机性,更多可能会更随机;然而,一些系统(busybox ash,例如)比其他系统更显着地限制了这种随机性

mktemp is not standard, but it does exist on many platforms. The "X"s will generally get converted into some randomness, and more will probably be more random; however, some systems (busybox ash, for one) limit this randomness more significantly than others

顺便说一句,安全创建临时文件不仅对 shell 脚本很重要.这就是为什么python有tempfile,perl有File::Temp,ruby 有 Tempfile 等...

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天全站免登陆