如何在bash中创建具有特定扩展名的临时文件? [英] How can I create a temp file with a specific extension in bash?

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

问题描述

我正在编写一个shell脚本,并且需要创建一个具有特定扩展名的临时文件.

I'm writing a shell script, and I need to create a temporary file with a certain extension.

我尝试过

tempname=`basename $0`
TMPPS=`mktemp /tmp/${tempname}.XXXXXX.ps` || exit 1

tempname=`basename $0`
TMPPS=`mktemp -t ${tempname}` || exit 1

两者都不起作用,因为第一个创建的文件名带有文字"XXXXXX",第二个没有提供扩展名选项.

neither work, as the first creates a file name with a literal "XXXXXX" and the second doesn't give an option for an extension.

我需要扩展名,以便预览不会拒绝打开文件.

I need the extension so that preview won't refuse to open the file.

我最终希望将pid和mktemp结合使用,以确保安全:

I ended up going with a combination of pid and mktemp in what I hope is secure:

tempname=`basename $0`
TMPTMP=`mktemp -t ${tempname}` || exit 1
TMPPS="$TMPTMP.$$.ps" 
mv $TMPTMP $TMPPS || exit 1

它很容易遭到拒绝服务攻击,但是我认为没有更严重的事情了.

It is vulnerable to a denial of service attack, but I don't think anything more severe.

推荐答案

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.

这篇关于如何在bash中创建具有特定扩展名的临时文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆