且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在bash中创建具有特定扩展名的临时文件?

更新时间:2022-11-28 12:33:54

mktemp的最新版本提供-后缀:

Recent versions of mktemp offer --suffix:

   --suffix=SUFF
          append SUFF to TEMPLATE.  SUFF must not contain slash.  This option is implied if TEMPLATE does not end in X.

$ mktemp /tmp/banana.XXXXXXXXXXXXXXXXXXXXXXX.mp3
/tmp/banana.gZHvMJfDHc2CTilINNuq2P0.mp3

我相信这需要coreutils> = 8左右.

I believe this requires coreutils >= 8 or so.

如果您创建一个不带后缀的临时文件(较旧的mktemp版本),并且要重命名该文件以附加一个后缀,那么您可能要做的最少的事情就是检查该文件是否已存在.它不能保护您免受竞争状况的侵害,但是可以保护已经存在一段时间的此类文件.

If you create a temp file (older mktemp version) without suffix and you're renaming that to append one, the least thing you could probably do is check if the file already exists. It doesn't protect you from race conditions, but it does protect you if there's already such a file which has been there for a while.