Anchor(faq62)

How do I create a temporary file in a secure manner?

Good question. To be filled in later. (Interim hints: tempfile is not portable. mktemp exists more widely, but it may require a -c switch to create the file in advance; or it may create the file by default and barf if -c is supplied. Some systems don't have either command (Solaris, POSIX). There does not appear to be any single command that simply works everywhere.)

The traditional answer has usually been something like this:

   # Do not use!  Race condition!
   TEMPFILE=/tmp/myname.$$
   trap 'rm -f $TEMPFILE; exit 1' 1 2 3 15
   rm -f $TEMPFILE
   touch $TEMPFILE

The problem with this is: if the file already exists (for example, as a symlink to /etc/passwd), then the script may write things in places they should not be written. Even if you remove the file immediately before using it, you still have a RaceCondition: someone could re-create a malicious symlink in the interval between your shell commands.

Suggestion (remove if not universal): A temporary directory can be created that is unlikely to match an existing directory using the RANDOM variable as follows:

   TEMP_DIR=/tmp/$RANDOM
   mkdir $TEMP_DIR

This will make a directory of the form: /tmp/20445/. To decrease the chance of collision with an existing directory, the RANDOM variable can be used a number of times:

   TEMP_DIR=/tmp/$RANDOM-$RANDOM-$RANDOM
   mkdir $TEMP_DIR

This will make a directory of the form: /tmp/24953-2875-2182/ . This avoids a race condition because the mkdir is atomic, as we see in [:BashFAQ/045:FAQ #45].

Another not-quite-serious suggestion is to include C code in the script that implements a mktemp(1) command based on the mktemp(3) library function, compile it, and use that in the script. But this has a couple problems: