When you run a complex diagnostic command in a Linux terminal, the output is printed directly to the screen for you to read. If you want to save that data for later, you can use the standard > operator to redirect the output into a log file. However, standard redirection is a one-way street: it writes the file to the hard drive, but your terminal screen remains completely blank, meaning you cannot read the data in real-time. To split the output stream—printing it to your screen and saving it to a file simultaneously—you must use the tee command.
How the tee Command Works
The tee command gets its name from the T-splitter used in plumbing. It takes a single stream of raw text data and splits it perfectly in half, sending one copy to the terminal screen (Standard Output) and the other copy directly into a permanent file.
Because it operates on data streams, tee is almost never used by itself. It is usually chained to the end of another command using a “pipe” (|).
If you want to ping Google’s servers to test your network latency, and you want to watch the ping times on your screen while simultaneously logging the data to a text file for your boss, run:
ping google.com | tee network_log.txt
As the ping command fires, you will see every single line of output scroll down your terminal window perfectly normally. Behind the scenes, tee is quietly copying every single one of those lines into the network_log.txt file in real-time.
How to Append Data (Do Not Overwrite)
By default, the tee command is highly destructive. If you run the exact same ping command an hour later, tee will violently delete the original network_log.txt file and overwrite it with the new data.
If you are building an ongoing log file and want to add the new data to the very bottom of the existing file without destroying the old data, you must append the -a (append) flag.
ping google.com | tee -a network_log.txt
This tells the T-splitter to open the existing log file, scroll to the absolute bottom, and safely paste the new data there.
Bypassing sudo Redirection Errors
The most common and critical use case for tee is solving a notorious Linux permissions bug. If you try to write data into a highly restricted system file (like /etc/hosts) using a standard sudo echo "data" > /etc/hosts command, it will fail with a “Permission denied” error. The sudo privilege only applies to the echo part of the command, not the > redirection part.
To safely inject data into a root-owned file, you must pipe the data through tee running with elevated privileges:
echo "192.168.1.50 servers" | sudo tee -a /etc/hosts
This time, the text is generated normally, passed through the pipe, and the sudo tee command successfully forces the text into the restricted system file.