Linux /tmp

From Leo's Notes
Last edited on 17 November 2023, at 00:06.

Temporary files on Linux can be stored in various places. See file-hierarchy(7) for details about these two (and most other) directories of a Linux system.

/tmp /var/tmp /run /run/user/# /dev/shm
Typical behavior not preserved between reboots

Periodic cleanup may occur.

typically preserved between reboots.

Periodic cleanup may occur.

for non-persistent runtime data of long lived services such as locks, sockets, pid files Typically set as the XDG_RUNTIME_DIR.

Not preserved between reboots

A memory backed scratch space for programs.

Not preserved between reboots

Typical fs tmpfs, backed by RAM/swap backed by persistent filesystem tmpfs, backed by RAM/swap tmpfs, backed by RAM/swap On Linux, typically tmpfs
Access Writable by everyone Writable by everyone Writable to only privileged services Writable to only its user Writable by everyone

Typical mount options

/tmp and /var/tmp are typically mounted with the following options:

  • noexec - no programs can be executed
  • nosuid - no setuid bits can be set
  • nodev - no device nodes

In addition, all public temporary locations (including /tmp, /var/tmp, and /dev/shm) are typically chmod 1777. This grants anyone the ability to write there with new file's ownership defaulting to the owner's user and group.

Automatic cleanup

Automatic cleanup on systemd systems is done through the systemd-tmpfiles service.

Bind mounting /tmp over /var/tmp

In some scenarios, it may make sense to bind-mount /tmp over /var/tmp. This forces temporary files to one location. Some advantages with this approach include:

  • Simplify where temporary files are located and cleaned up
  • Reduce the risk of /var filling up

This can be implemented by running mount --bind /tmp /var/tmp or by adding to /etc/fstab:

/tmp /var/tmp none bind 0 0