Creating temporary files in bash

The mktemp(1) man page explains it fairly well:

Traditionally, many shell scripts take the name of the program with
the pid as a suffix and use that as a temporary file name. This kind
of naming scheme is predictable and the race condition it creates is
easy for an attacker to win. A safer, though still inferior, approach
is to make a temporary directory using the same naming scheme. While
this does allow one to guarantee that a temporary file will not be
subverted, it still allows a simple denial of service attack. For
these reasons it is suggested that mktemp be used instead.

In a script, I invoke mktemp something like

mydir=$(mktemp -d "${TMPDIR:-/tmp/}$(basename $0).XXXXXXXXXXXX")

which creates a temporary directory I can work in, and in which I can safely name the actual files something readable and useful.

mktemp is not standard, but it does exist on many platforms. The “X”s will generally get converted into some randomness, and more will probably be more random; however, some systems (busybox ash, for one) limit this randomness more significantly than others


By the way, safe creation of temporary files is important for more than just shell scripting. That’s why python has tempfile, perl has File::Temp, ruby has Tempfile, etc…

Leave a Comment