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