Using temporary files cleanly

If you need a temporary file in your script to store data for the script's run, it can be tempting to assume a fixed path for the file in /tmp:

# Store the current date for later
# Requires GNU/BSD `date` with non-POSIX %s format
date +%s > /tmp/myscript-timestamp

/tmp exists on virtually all Unix systems, which makes it a popular choice. However, this approach has some risks:

The name of the temporary directory is often available in the TMPDIR environment variable, which can improve this approach a little, while still using /tmp as a fallback:

date +%s > "${TMPDIR:-/tmp}"/myscript-timestamp

However, perhaps the best approach is the use of the mktemp tool, if it's available. It creates temporary files or directories, and prints the name of whatever it created. It should do this creation relatively safely, with a randomized name, and in a location and pattern that's consistent with the system's settings:

$ mktemp -d
/tmp/tmp.mmfGKhMxtv

We can use this to safely pick a temporary directory for our script each run:

tempdir=$(mktemp -d) || exit
date +%s > "$tempdir"/myscript-timestamp

Note that we abort the script if the temporary directory could not be created; || exit runs only if the mktemp command in the variable assignment fails.

mktemp is not a standard POSIX tool, so it's not guaranteed to be available, but it's very common on many Unix-like systems, including Linux and BSD. Use it if you can.