[Linux] Using mktemp Command is Safe for Creating tmp Files
In Linux, if you want to create tmp files under the /tmp directory, using the mktemp command allows you to create files safely.
How to Use mktemp
After mktemp, specify any filename + three or more “X”s, and the parts where you specified “X” will be replaced with appropriate character strings.
$ mktemp /tmp/XXXXXX
/tmp/DCz1yP
By the way, mktemp can work without arguments, but since TMPDIR might be a directory other than /tmp depending on the distribution or macOS, it’s safer to specify the directory.
[Standard] Combining mktemp with mv or ln
When filenames are fixed, executing the same command overwrites the same file, making content consistency unreliable. So it’s fairly common practice to create a temporary file and then use mv (last one wins) or ln (first one wins).
Practical Example Combining mktemp and mv
TMPFILE=`mktemp`
some processing > "$TMPFILE"
mv "$TMPFILE" needed_file
Practical Example Combining mktemp and ln
TMPFILE=`mktemp`
ln "$TMPFILE" needed_file_fixed
some processing > needed_file
[Aside] Can't Add Suffix on macOS
When you run mktemp /tmp/XXXXXX.csv on macOS, it creates a file called XXXXXX.tsv, but when run on Amazon Linux:
[ec2-user@aws ~]$ mktemp /tmp/XXXXXX.csv
/tmp/DCz1yP.csv
A random filename is assigned like this. I tried it on macOS and thought “what’s this?”
On Unix-type OSes, suffixes don’t matter much, so mktemp /tmp/XXXXXX is pretty normal. On Mac OS X, using GNU coreutils’ gmktemp gives the same behavior as Linux.
$ brew install coreutils
$ gmktemp /tmp/XXXXX.csv
/tmp/cdWSV.csv
That’s all from the Gemba, where I want to safely create tmp files with the mktemp command.
Reference Information
- Man page of MKTEMP
- GNU Coreutils: 18.4 mktemp: Create temporary files and directories
- Safe Methods for Creating and Deleting Temporary Files - Extended POSIX Shell Script Advent Calendar 2013 - Criticism Blog
- Man page of OPEN
- Man page of MKSTEMP
That’s all from the Gemba.