tags:

views:

103

answers:

1

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.

A: 
tempfile="$$.extension"

edit, better yet

tempfile="/tmp/$$.extension"
David V.
do you know if this is secure against race conditions, or should I create a temp directory first?
cobbal
that will only give you a temporary filename, now you do whatever you want with it.$$ is expanded by you pid, for most uses that should be unique enough.
David V.
I'm not sure how there could be a race condition, since $$ is expanded by your pid, which is unique at that moment. you could prefix your temporary filename, like tmp="/tmp/myscript-$$.extension" so that you know you can safely overwrite a temp file if it's still hanging there when your script runs.
David V.
from man mktemp: *"The mktemp utility is provided to allow shell scripts to safely use temporary files. 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."* I think this will work with a little modification though
cobbal
have a look here : http://www.gnu.org/software/coreutils/manual/html_node/mktemp-invocation.htmlespecially that part : mktemp --suffix=.txt file-XXXX
David V.
seems to not work on my version of mktemp (default that comes with OS X 10.6) although that is exactly what I'm looking for.
cobbal
I linked you to the GNU version of mktemp, maybe there's some functionality absent from the OSX version.I did some research and here's what you want (I hope)tmp="$(mktemp myscriptXXXXXXXXXXXXX).myextension"
David V.