Creating and Using Temporary Files

While pipes eliminate much of the need for them, temporary files are still sometimes required. Unlike some operating systems, Unix has no notion of scratch files that are somehow magically removed when they are no longer needed. Instead, it provides two special directories, /tmp and /var/tmp (/usr/tmp on older systems), where such files are normally stored so that they do not clutter ordinary directories in the event that they are not cleaned up. On most systems, /tmp is cleared when the system boots, but /var/tmp must survive reboots because some text editors place backup files there to allow data recovery after a system crash.

Because /tmp is so heavily used, some systems make it a memory-resident filesystem for faster access, as shown in this example from a Sun Solaris system:

$ df /tmp                                
            Show disk free space for /tmp
Filesystem           1K-blocks      Used Available Use% Mounted on
swap                  25199032    490168  24708864   2% /tmp

Putting the filesystem in the swap area means that it resides in memory until memory resources run low, at which point some of it may be written to swap.

Tip

The temporary-file directories are shared resources, making them subject to denial of service from other jobs that fill up the filesystem (or swap space), and to snooping or to file removal by other users. System management may therefore monitor space usage in those directories, and run cron jobs to clean out old files. In addition, the sticky permission bit is normally set on the directory ...

Get Classic Shell Scripting now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.