How can I create a temp file with a specific extension in bash?
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开发者_StackOverflow社区 -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.
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.
How about this one:
echo $(mktemp $TMPDIR/$(uuidgen).txt)
All of these solutions except --suffix (which isn't always available) have a race condition. You can eliminate the race condition by using mktemp -d to create a directory, then putting your file in there.
mydir=`mktemp -d`
touch "$mydir"/myfile.ps
MacOS Sierra 10.12 doesn't have --suffix option, so I suggest workaround:
tempname=`basename $0`
TMPPS_PREFIX=$(mktemp "${TMPDIR:-/tmp/}${tempname}.XXXXXX")
TMPPS=$(mktemp "${TMPPS_PREFIX}.ps")
rm ${TMPPS_PREFIX}
echo "Your temp file: ${TMPPS}"
Here's a more portable solution (POSIX-compatible):
temp=$(mktemp -u).ps
: >"$temp"
The first line runs mktemp
without creating the file, then sets temp
to the generated filename with .ps
appended. The second line then creates it; touch "$temp"
can be used instead if you prefer it.
EDIT: Note that this doesn't have the same permissions as it creates it using shell redirection. If you need it to be unreadable by other users, you can use chmod
to set it manually.
For macOS -
brew install coreutils
Then -
gmktemp --suffix=.ps
On the macOS 13, mktemp
still doesn't support --suffix
, I rename it after make the file, it seems working fine.
$ tmp=`mktemp -t prefix`
$ mv $tmp $tmp.txt
$ ls $tmp.txt
/var/folders/..../T/prefix.xxxx.txt
精彩评论