Sample Header Ad - 728x90

Why is there no mktemp command in POSIX?

27 votes
2 answers
4085 views
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](https://www.gnu.org/software/coreutils/manual/html_node/mktemp-invocation.html#mktemp-invocation) and [this Signs of Triviality blog post](https://www.netmeister.org/blog/mktemp.html) 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](https://stackoverflow.com/a/2792789/906070) . If you really want to create a temp file both safely _and_ portably, you have to resort to [ugly kludges](https://unix.stackexchange.com/a/181996/37849) 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?
Asked by Psychonaut (974 rep)
Oct 16, 2020, 09:17 AM
Last activity: Feb 28, 2025, 09:00 AM