linux - 在 bash 中创建临时文件

标签 linux bash unix

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

我通常只是将它们命名为我想到的任何名称,例如 tempfile-123,因为它会在脚本结束时被删除。除了覆盖当前文件夹中可能的 tempfile-123 之外,这样做有什么缺点吗?或者以更谨慎的方式创建临时文件有什么好处?

最佳答案

mktemp(1) 手册页很好地解释了它:

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 之类的东西

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

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

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


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

关于linux - 在 bash 中创建临时文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10982911/

相关文章:

linux - 如何在循环中附加到 screen session ?

文件的正则表达式匹配并重命名+覆盖旧文件

c - 如何在 fork-exec 之后在两个进程之间创建套接字

unix - 您可以使用正则表达式 grep 文件并只输出一行的匹配部分吗?

linux - 在 shell 脚本中将二进制数据转换为十六进制

c - 可变堆栈大小

linux - Linux 上的 GZip 来压缩文本文件中指定的文件

linux - 如何从 Bash 脚本列出目标 PID 的孙子 PID?

c - 将简单的套接字变成 SSL 套接字

c# - 单声道(Linux、C#): DLL in same folder can not be found (System. DllNotFoundException)