Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a temp file with a specific extension in bash?

Tags:

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

I've tried

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

and

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

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.

Edit: 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.

like image 869
cobbal Avatar asked Mar 10 '10 19:03

cobbal


People also ask

How to create temp file in shell script?

A temp file can be created by directly running mktemp command. The file created can only be read and written by the file owner by default. To ensure the file is created successfully, there should be an OR operator to exit the script if the file fails to be created.


2 Answers

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 

I believe this requires coreutils >= 8 or so.

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.

like image 117
basic6 Avatar answered Oct 06 '22 04:10

basic6


How about this one:

echo $(mktemp $TMPDIR/$(uuidgen).txt) 
like image 36
Stephan Avatar answered Oct 06 '22 04:10

Stephan