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 /tmpprogramname.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.

download.eps
 $ ls -l 'mktemp'  ...

Get Shell Scripting: Expert Recipes for Linux, Bash, and More now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.