Using “tee” to write to files and the terminal May 17, 2007Posted by Carthik in administration, commands, snippets, ubuntu.
The utility “tee” is very useful for plumbing on the command line. Curiously enough, it gets its name from the T-splitter used in plumbing, shown below:
Say you want to run a command, and be able to see the output and errors on the screen, and be able to save them to a file. That’s where tee comes in, so you could do a:
$sudo apt-get upgrade 2>&1 | tee ~/apt-get.log
…to run apt-get upgrade and save the output and errors to the file apt-get.log in your home directory.
Purists please excuse the following explanation :) The “2” refers to the “tap” from which the errors pour out (called stderr). The “1” refers to the tap from which the output pours out. The 2>&1 makes the errors to also pour out of the output tap. So then stderr goes to stdout. The pipe “|” redirects the output to tee. Now tee splits the output of the previous command two ways, and puts it both in ~/apt-get.log and in the standard output, which happens to be your screen/terminal.
tee is also handy when you have a small permissions problem. Say you want to write some text to a file “filename.txt” owned by the “root” user – you would just use something like:
$sudo vim filename.txt
and then change the file, right?
Now suppose you want to echo what you write, and write the file, all in one command, you then can use tee thusly:
$echo "localhost 127.0.0.1" | sudo tee filename.txt > /dev/null
This would write the text “localhost 127.0.0.1″ to the file filename.txt which is not owned by you. The output of tee itself will go to /dev/null (nothingness) instead of the standard output, which is your terminal.
Don’t lose sleep over this, but someday it will come handy, and when you can figure out why the “sudo” does not apply after the “>” in your command, remember tee and come back here.
For all your command line redirecting needs, and to learn to wield pipes and tees like nunchakus read this excellent page.