When executing scripts or compiling code in the Linux terminal, you often need to save the output to a log file for future reference. While you can easily redirect output using the > operator, doing so completely silences the terminal, meaning you cannot see the progress in real-time. If you want to log the output to a file and watch it on your screen simultaneously, you need to use the tee command.
How the tee Command Works
The tee command reads from standard input (stdin) and writes it to both standard output (stdout, which is your screen) and one or more files at the same time. Think of it like a T-splitter in plumbing, sending water in two different directions simultaneously.
To use it, you pipe (|) the output of your initial command directly into tee, followed by the name of the file you want to write to.
Basic Example
Suppose you want to ping a server, save the results to a file named ping_test.log, and still watch the pings happen on your screen.
ping google.com | tee ping_test.log
As the ping command runs, the text will appear in your terminal exactly as it normally would. However, if you press Ctrl + C to stop the ping and then open the ping_test.log file, you will see that every single line was also perfectly recorded.
How to Append to an Existing File
By default, the tee command will completely overwrite the target file if it already exists. If you are running a script multiple times and want to add the new output to the bottom of the existing log file, you must use the -a (append) flag.
ping google.com | tee -a ping_test.log
Writing with Sudo Privileges
A common problem in Linux occurs when you try to write command output to a file owned by the root user using standard redirection (e.g., sudo echo "text" > /etc/file.conf). This will fail because the redirection operator (>) does not inherit the sudo privileges. The tee command solves this perfectly:
echo "text" | sudo tee /etc/file.conf