is /tmp guaranteed to exist?

The FHS mandates that /tmp exist, as does POSIX so you can rely on its being there (at least on compliant systems; but really it’s pretty much guaranteed to be present on Unix-like systems). But you shouldn’t: the system administrator or the user may prefer other locations for temporary files. See Finding the correct tmp dir on multiple platforms for more details.


In practice, /tmp is pretty much guaranteed to exist. However, even if it exists, that doesn't mean you should put temporary files there.

The standard convention is to use the TMPDIR environment variable. If it exists, it points to a directory for temporary files. If it doesn't exist, put temporary files in /tmp.

In a shell script, you can use "${TMPDIR:-/tmp}" as the temporary file location: this expands to the value of TMPDIR if it's set¹, and to /tmp otherwise. Or you can set TMPDIR conditionally in case it's unset, with the command

: "${TMPDIR:=/tmp}"

and then create temporary files inside "$TMPDIR".

Note that any application can create files under /tmp or $TMPDIR. Furthermore this directory may be shared between users, so you need to take care about permissions when creating a file. Many systems (Linux, *BSD) have a command mktemp which creates files safely in the right directory. It's generally a good idea to use mktemp to create temporary files and directory — especially from a shell script, where it's impossible to create a file securely in a shared directory due to the possibility of symlink attacks (mkdir is fine if you handle errors correctly).

¹ and non-empty — if the variable is empty then it isn't usable as is anyway, and it's generally a good idea to treat empty or unset variables in the same way if they're supposed to contain a file name.


Although it's very likely to exist, you should check for another reason: it's not guaranteed to be big. On many systems, /tmp is backed by RAM rather than disk, and likely to be limited to a few GB. (On Fedora systems, it's half of RAM by default.) So, you should check not just for existence, but whether there's room to put whatever you intend to put there.

If you have something large, use /var/tmp/.

Tags:

Tmp