How to use the “tee” command

Sunday, May 19, 2013

How to use the “tee” command
The tee command is a little tool which is very useful but often overlooked. The function of tee doesnt sound very exciting, it was created for only one purpose: write STDIN to STDOUT and a file. But tee actually can do a lot for you. Basically if you want to redirect STDOUT of a program as well as printing it to the screen, tee is the right tool to use. A very simple example would be:
grep “anyString” file.txt | tee result.txt

This command searches for all occurrences of “anyString” in the file file.txt and pipes it to tee which prints to the screen and writes it to the file result.txt. Normally, the example above isnt used much but you can do more with tee. For example, if you want to write some string into two files at once, the command with tee you can use is:
echo “some text” | tee file1 > file2

Now we’ve passed our example text to tee that writes it to file1 and STDOUT which we’ve redirected to file2. And that results to both files containing the same text. Thats how tee can help you speed up your workflow when piping together multiple operations. And of course, you can extend this to writing into 3, 4, … or more files at once:
echo “some text” | tee file1 | tee file2 > file3

Another thing tee can help you is to avoid one problem when using sudo. The normal output redirection operator is always executed with your user privileges, also when you write a sudo in front of the command which generates the STDOUT text. In other words, this will fail if you dont have the permission to write to that file:
sudo echo “something” > bar

But with tee, everything will go well:
echo “something” | sudo tee bar

One last hint at the very end: tee behaves like the output redirection operator > so if the file already exists it will be overwritten. To make tee behave like the append operator >> use parameter -a.