Temporary files

Temporary files are the files that are needed for a short interval of time while an application is running. Such files are being used to keep intermediate results of running a program and they are no longer needed after the program execution is complete. In shell, we can create temporary files using the mktemp command.

Creating a temporary file using mktemp

The mktemp command creates a temporary file and prints its name on stdout. Temporary files are created by default in the /tmp directory.

The syntax of creating a temporary file is as follows:

$ mktmp
/tmp/tmp.xEXXxYeRcF

A file with the name tmp.xEXXxYeRcF gets created into the /tmp directory. We can further read and write into this file in an application for temporary use. Using the mktemp command instead of using a random name for a temporary filename avoids accidental overwrite of an existing temporary file.

To create a temporary directory, we can use the -d option with mktemp:

$ temp_dir=mktemp -d
$ echo $temp_dir
/tmp/tmp.Y6WMZrkcj4

Furthermore, we can explicitly delete it as well:

$ rm -r /tmp/tmp.Y6WMZrkcj4

We can even specify a template to use for a temporary file by providing an argument as name.XXXX. Here, name can be any name by which a temporary file should begin, and XXXX tells the length of a random character to be used after a dot (.). In general, while writing an application if temporary files are needed, the application name is given as the temporary file name.

For example, a test application needs to create a temporary file. To create a temporary file, we will use the following command:

$ mktemp test.XXXXX
test.q2GEI

We can see that the temporary file name begins with test and contains exactly five random letters.

Note

The time when temporary files will be cleaned up is distribution-specific.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.66.132