Why do we need mktemp?

mktemp randomizes the name. It is very important from the security point of view.

Just imagine that you do something like:

echo something > /tmp/temporary-file

in your root-running script.

And someone (who has read your script) does

ln -s /etc/passwd /tmp/temporary-file

before.

This results in /etc/passwd being overwritten, and potentially it can mean different unpleasant things starting from the system becomes broken, and ending with the system becomes hacked (when the input something could be carefully crafted).

The mktemp command could help you in this situation:

TEMP=$(mktemp /tmp/temporary-file.XXXXXXXX)
echo something > ${TEMP}

Now this ln /etc/passwd attack will not work.

A brief insight into the history of mktemp: The mktemp command was invented by the OpenBSD folks, and first appeared in OpenBSD 2.1 back in 1997. Their goal was to improve the security of shell scripts. Previously the norm had been to add $$ to temporary file names, which was absolutely insecure. Now all UNIX/Linux systems have either mktemp or its alternatives, and it became standard de-facto. Funny enough, the mktemp C function was deprecated for being unsecure.


You often want a "scratchpad file" (or directory). Moreover, you might need several such files at the same time, and you don't want to bother figuring out how to name them so there's no conflict.

"mktemp" fits the bill :)