Categories
Linux Mastering Development

Why is there no mktemp command in POSIX?

One of the most common things shell scripts need to do is to create and manipulate temporary files. Doing so safely is a pain, since you need to avoid name clashes, avoid race conditions, make sure the file has the correct permissions, etc. (See the GNU Coreutils manual and this Signs of Triviality blog post for a more detailed discussion of these issues.) Most Unix-like operating systems solve this problem by providing a mktemp command that takes care of all these gotchas. However, the syntax and semantics of these mktemp commands are not standardized. If you really want to create a temp file both safely and portably, you have to resort to ugly kludges such as the following:

tmpfile=$(
  echo 'mkstemp(template)' |
    m4 -D template="${TMPDIR:-/tmp}/baseXXXXXX"
) || exit

(This workaround exploits the fact that the macro processor m4 is part of POSIX, and m4 exposes the C standard library function mkstemp() which is also defined by POSIX.)

Given all this, why hasn’t POSIX standardized a mktemp command, guaranteeing its presence and at least certain aspects of its behaviour? Is this a glaring oversight on the part of the POSIX committee, or has the idea of standardizing a mktemp actually been discussed by the committee and rejected for some technical or other reason?

Leave a Reply

Your email address will not be published. Required fields are marked *