When writing a shell script, we often need to store temporary data. The location that is best suited for storing temporary data is/tmp (the contents of the directory are emptied after the system restarts). There are two ways to generate standard file names for temporary data. 2.10.1 Practical Exercises
Perform the following steps to create a temporary file and perform a different naming operation.
To create a temporary file:
$ Filename= ' mktemp '
$ echo $filename
/TMP/TMP.8XVHKJF5FH
The code above creates a temporary file and prints out the name of the file stored in $filename.
To create a temporary directory:
$ Dirname= ' mktemp-d '
$ echo $dirname
tmp. Ni8xzw7vrx
The code above creates a temporary directory and prints out the name of the directory stored in $dirname.
If you simply want to generate a file name and do not want to create the actual file or directory, the following methods are:
$ Tmpfile= ' mktemp-u '
$ echo $tmpfile
/tmp/tmp. rsgmilrpct
The file name is stored in $tmpfile, but the corresponding file is not created.
To create a temporary file name from a template:
$mktemp test.xxx
TEST.2TC
2.10.2 Working principle
The Mktemp command is very simple to use. It generates a temporary file and returns its file name (if the directory is created, the directory name is returned).
If a custom template is provided, x is replaced by random characters (letters or numbers). Note that the prerequisite for mktemp to work properly is to ensure that there are only 3 x in the template.