The tee
command in Linux reads from standard input and writes to both standard output and one or more files simultaneously. It acts like a “T-splitter” for data streams, allowing you to view output in real-time while saving it to a file.
Contents
Save Output to a File While Viewing ItAppend to a File Instead of OverwritingWrite to Multiple FilesUse with sudo to Write to Protected FilesCapture Intermediate Pipeline OutputCombine with grep for Filtered LoggingIgnore Interrupt Signals (Continue Writing)Split Output into Files and TerminalUse with Process SubstitutionSuppress Terminal OutputUse with df to Monitor Disk Space
This is especially useful for debugging, logging, or monitoring command output without disrupting pipelines. Below are practical examples to master tee:
Save Output to a File While Viewing It
ls -l | tee directory_list.txt
- Lists directory contents and saves the output to
directory_list.txt
.
Append to a File Instead of Overwriting
echo "New log entry" | tee -a app.log
-a
appends the text toapp.log
instead of overwriting it.
Write to Multiple Files
dmesg | tee system.log boot.log
- Saves the kernel ring buffer output to both
system.log
andboot.log
.
Use with sudo
to Write to Protected Files
echo "127.0.0.1 test.local" | sudo tee -a /etc/hosts
- Uses
sudo
to append a line to the protected/etc/hosts
file.
Capture Intermediate Pipeline Output
grep "ERROR" app.log | tee errors.txt | wc -l
- Saves error lines to
errors.txt
while counting them withwc -l
.
Combine with grep
for Filtered Logging
journalctl -u nginx | tee nginx_logs.txt | grep "404"
- Saves full Nginx logs to
nginx_logs.txt
while filtering for “404” errors.
Ignore Interrupt Signals (Continue Writing)
ping google.com | tee -i ping_results.txt
-i
ensurestee
continues writing even if interrupted (e.g.,Ctrl+C
).
Split Output into Files and Terminal
ls /usr/bin | tee all_programs.txt featured_programs.txt
- Lists programs in
/usr/bin
and saves the output to two files.
Use with Process Substitution
ls -l | tee >(gzip > dirlist.gz) >(awk '{print $9}' > filenames.txt)
- Saves raw output to
dirlist.gz
(compressed) and filenames tofilenames.txt
.
Suppress Terminal Output
curl -s http://example.com | tee response.html > /dev/null
- Downloads a webpage silently and saves it to
response.html
.
Use with df
to Monitor Disk Space
df -h | tee disk_usage.log
Displays disk usage statistics and logs them to disk_usage.log
.
Key Notes:
- Overwriting: By default,
tee
overwrites files. Use-a
to append. - Permissions: Use
sudo tee
when writing to system-protected files. - Pipelines: Place
tee
anywhere in a pipeline to capture intermediate data.
Featured Image: Wikimedia, CC BY-SA 4.0