Mastering the tee Command: 7 Practical Linux Examples
This guide explains how the Linux tee command reads from standard input and simultaneously writes to both a file and the screen, providing seven detailed examples that cover basic usage, writing to multiple files, silent output, appending, sudo integration, piping between commands, and using tee within vim.
The tee command is a Unix utility that reads data from standard input and writes it to one or more files while also sending the same data to standard output, making it useful for logging and chaining commands.
Example 1: Basic Usage
Display the output of lsblk and save it to devices.txt at the same time: lsblk | tee devices.txt You can verify the file content with:
cat devices.txtExample 2: Writing to Multiple Files
Redirect the output of hostnamectl to two files simultaneously: hostnamectl | tee file1.txt file2.txt The command prints the system hostname details to the terminal and stores the same output in file1.txt and file2.txt.
Example 3: Silent Output to a File
Suppress screen output by redirecting tee’s output to /dev/null while still saving to a file:
df -Th | tee file4.txt > /dev/nullExample 4: Appending Output to a File
By default tee overwrites the target file. Use the -a or --append option to add new data without erasing existing content:
lsblk | tee file1.txt
date | tee -a file1.txt
cat file1.txtExample 5: Using tee with sudo
When a command needs root privileges to write to a protected file, prepend sudo to tee:
echo "10.200.50.20 db-01" | sudo tee -a /etc/hostsExample 6: Piping tee Between Commands
Chain commands by feeding tee’s output directly into another command, for instance counting lines after filtering:
grep 'root' /etc/passwd | tee /tmp/passwd.tmp | wc -lThe filtered lines are saved to /tmp/passwd.tmp and the line count is displayed.
Example 7: Using tee Inside vim
When editing a root‑owned file in vim without sudo, write the buffer through tee to gain the necessary permissions:
:w !sudo tee %Conclusion
The tee command is a versatile tool for duplicating command output, supporting basic logging, multi‑file writes, silent operation, appending, privilege escalation with sudo, and integration into pipelines or editors like vim.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
