Linux Tweaks, HowTo's and Reviews

The Linux tee command is a way to write the standard output to a file. Or, to quote from the man page documentation,

tee - read from standard input and write to standard output and files

This is a little different from redirecting output to a file. In this case, the output is still send to standard out, but an additional copy is sent to create your text file. There are some good examples of how this can be useful, shown in the info documentation for tee. To view the info page, open a terminal window and enter

info coreutils 'tee invocation'

To understand the basic usage of the tee command, go to a terminal window and navigate to a directory that contains a small number of files. You can then use the ls and tee commands to create a text file that contains a listing of the files in that directory.

ls | tee listing.txt

You can also append a file using the -a switch. This will insert the output lines at the bottom of a pre-existing file.

ls | tee -a listing.txt

An example of when tee comes in handy is when you want to create a simple text file as root from your user account. I used it to create the fully qualified domain name file for my Apache configuration. You would think you could use

sudo echo "ServerName localhost" > /etc/apache2/conf.d/fqdn

but that doesn't work because the sudo only affects the echo command and not the output redirection.

Instead, you can use tee like this.

echo "ServerName localhost" | sudo tee /etc/apache2/conf.d/fqdn

That command succeeds in creating the fqdn file with the desired content.

Do you know some other creative ways to use tee? Let me know in the comments.