With judicious use of tricks like pipes, redirects, and process substitution in modern shells, it’s very often possible to avoid using temporary files, doing everything inline and keeping them quite neat. However when manipulating a lot of data into various formats you do find yourself occasionally needing a temporary file, just to hold data temporarily.
A common way to deal with this is to create a temporary file in your home
directory, with some arbitrary name, something like test
or working
:
$ ps -ef >~/test
If you want to save the information indefinitely for later use, this makes
sense, although it would be better to give it a slightly more instructive name
than just test
.
If you really only needed the data temporarily, however, you’re much better to
use the temporary files directory. This is usually /tmp
, but for good
practice’s sake it’s better to check the value of TMPDIR
first, and only use
/tmp
as a default:
$ ps -ef >"${TMPDIR:-/tmp}"/test
This is getting better, but there is still a significant problem: there’s no
built-in check that the test
file doesn’t already exist, perhaps being used
by some other user or program, particularly another running instance of the
same script.
To that end, we have the mktemp
program, which creates an empty
temporary file in the appropriate directory for you without overwriting
anything, and prints the filename it created. This allows you to use the file
inline in both shell scripts and one-liners, and is much safer than specifying
hardcoded paths:
$ mktemp
/tmp/tmp.yezXn0evDf
$ procsfile=$(mktemp)
$ printf '%s\n' "$procsfile"
/tmp/tmp.9rBjzWYaSU
$ ps -ef >"$procsfile"
If you’re going to create several such files for related purposes, you could
also create a directory in which to put them using the -d
option:
$ procsdir=$(mktemp -d)
$ printf '%s\n' "$procsdir"
/tmp/tmp.HMAhM2RBSO
On GNU/Linux systems, files of a sufficient age in TMPDIR
are cleared on boot
(controlled in /etc/default/rcS
on Debian-derived systems,
/etc/cron.daily/tmpwatch
on Red Hat ones), making /tmp
useful as a general
scratchpad as well as for a kind of relatively reliable inter-process
communication without cluttering up users’ home directories.
In some cases, there may be additional advantages in using /tmp
for its
designed purpose as some administrators choose to mount it as a tmpfs
filesystem, so it operates in RAM and works very quickly. It’s also common
practice to set the noexec
flag on the mount to prevent malicious users from
executing any code they manage to find or save in the directory.