mktemp
It is often useful to be able to create a temporary file, which can be guaranteed to be unique. Many scripts use /tmp/programname.$$ for temporary files, where $$ is a special variable that returns the PID of the currently running process. This is often sufficient, but not truly robust. For example, if you read and write from /tmp/programname.$$, a malicious user could create lots of files in /tmp — programname.1, programname.2, and so on, such that creation of /tmp/programname.$$ fails (and that may not be easily checked for), the script writes data to a file owned by an untrusted user, or it reads data from a file provided by an untrusted user.
A truly robust solution must check that the filename is not in use and create that file for you before returning with the name of the file. mktemp does just that, creating either a file or a directory, whichever you require.
mktemp will, by default, create a file in the /tmp directory and return its name on standard output. However, you can specify your own template for the created file; the default template is $TMPDIR/tmp.XXXXXXXXXX, or /tmp/tmp.XXXXXXXXXX if $TMPDIR is not defined — that is, /tmp/tmp. followed by 10 randomly generated characters (upper and lowercase letters, and digits), but mktemp /var/tmp/helloXXX will create a file in /var/tmp with a name starting with “hello” followed by three random characters.
$ ls -l 'mktemp' ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access