TrumanWong

tempfile

Name temporary files in shell

Supplementary instructions

Sometimes when writing a Shell script, you need to temporarily store data. The most suitable location for storing temporary file data is /tmp, because all the contents in this directory will be cleared after the system is restarted. Here are two ways to generate standard filenames for temporary data.

tempfile command

The tempfile command is only included by default in Debian-based distributions, such as Ubuntu. Other distributions do not have this command.

Use the tempfile command to name a temporary file:

temp_file_name=$(tempfile)

Use a file name with a random number as the temporary file name:

temp_file_name="/tmp/file_$RANDOM"

$RANDOM is an environment variable that returns a random number.

$$Variables

If you have a Linux distribution without the tempfile command, you can also use your own temporary file name:

temp_file_name="/tmp/file.$"

$$ is a system predefined variable that displays the process number of the current process. Adding .$$ as the suffix will be expanded to the process ID of the currently running script.