linux - 在 bash 中创建临时文件

有没有客观上更好的方法在 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等等……

https://stackoverflow.com/questions/10982911/

相关文章:

python - 如何在 Python 中直接获取字典键作为变量(而不是通过从值中搜索)?

python - 在python中将一个列表插入另一个列表的语法是什么?

python - 我可以单独使用 Flask app.run() 为多个客户端提供服务吗?

c - 使用 gcc 命令行从 .c 文件构建 .so 文件

c - 在 Linux 中测量时间 - 时间 vs 时钟 vs getrusage vs clock

python - 从 django 的查询集中获取第一个对象的最快方法?

python - 如何编写好的/正确的包 __init__.py 文件

c - 写入 .txt 文件?

python - 如果在 Python 中为 None,是否有返回默认值的简写?

mysql - 有没有办法只安装mysql客户端(Linux)?