Temporary Files in Linux and the tee Command

Temporary Files in Linux and the tee Command

When working in the Linux shell, temporary files can be created using various methods. In the example below, two temporary files are created using the ll command, which lists the files in the current directory.

[root @ aoi dir.BEEbII5] # ll
total 8
-rw -------. 1 root root 44 Nov 20 08:24 temp.D3JWPR
-rw -------. 1 root root 44 Nov 20 08:24 temp.n0IElP

These files are created with the same permissions and ownership, and their sizes are identical. To verify the contents of these files, we can use the cat command.

[root @ aoi dir.BEEbII5] # cat temp.D3JWPR
This is a test line of data for temp.D3JWPR
[root @ aoi dir.BEEbII5] # cat temp.n0IElP
This is a test line of data for temp.n0IElP

The tee Command

The tee command is a powerful tool for sending data to multiple destinations simultaneously. By default, the tee command writes the input data to a file specified by the user, and also sends the data to the standard output (STDOUT).

[root @ aoi dir.BEEbII5] # date | tee wz
Wed Nov 20 08:27:54 CST 2013
[root @ aoi dir.BEEbII5] # cat wz
Wed Nov 20 08:27:54 CST 2013

In this example, the date command is used to generate a date string, which is then piped to the tee command. The tee command writes the date string to the file wz and also sends it to the standard output.

Redirecting Output with tee

The tee command can also be used to redirect the output of a command to a file, while still sending the output to the standard output. This is demonstrated by the following example, where the who command is used to generate a list of users currently logged in, and the output is redirected to the file wz using the tee command.

[root @ aoi dir.BEEbII5] # who | tee wz
root pts/1 2013-11-20 03:18 (192.168.1.100)
[root @ aoi dir.BEEbII5] # cat wz
root pts/1 2013-11-20 03:18 (192.168.1.100)

Appending Data to a File with tee

By default, the tee command overwrites the contents of the output file if it already exists. However, this behavior can be modified by using the -a option, which appends the new data to the end of the file instead of overwriting it.

[root @ aoi dir] # tee -a wz < data.txt

This command appends the contents of the file data.txt to the end of the file wz.