The tee Command
In this page:
Writing to a File and the Screen at Once
tee reads from stdin and writes an identical copy both to the named file and back out to stdout, so the data keeps flowing to the next stage of a pipeline while also being saved.
Example: Writing to a File and the Screen at Once
#!/bin/bash
echo "important result" | tee result.txt
echo "file contents:"
cat result.txt
rm -f result.txt
Login to try C/C++/Java/PHP code in the editor
Appending Instead of Overwriting
By default tee truncates the target file just like >. Pass -a to append instead, mirroring the difference between > and >> for plain redirection.
Example: Appending Instead of Overwriting
#!/bin/bash
echo "first" | tee notes.txt > /dev/null
echo "second" | tee -a notes.txt > /dev/null
cat notes.txt
rm -f notes.txt
Login to try C/C++/Java/PHP code in the editor
Writing to Multiple Files
tee accepts more than one filename and writes an identical copy of its input to each one, which is handy for fanning output out to several logs at once.
Example: Writing to Multiple Files
#!/bin/bash
echo "shared output" | tee file_a.txt file_b.txt > /dev/null
echo "file_a: $(cat file_a.txt)"
echo "file_b: $(cat file_b.txt)"
rm -f file_a.txt file_b.txt
Login to try C/C++/Java/PHP code in the editor
Using tee to Inspect a Pipeline
Because tee passes its input through unchanged, you can insert it into the middle of an existing pipeline purely to capture an intermediate snapshot for debugging, without changing the pipeline's final result.
Example: Using tee to Inspect a Pipeline
#!/bin/bash
printf "3\n1\n2\n" | sort -n | tee sorted.txt | tr '\n' ','
echo
echo "snapshot saved by tee:"
cat sorted.txt
rm -f sorted.txt
Login to try C/C++/Java/PHP code in the editor
- Assuming
teealways overwrites the file; by default it truncates, buttee -ais needed to append instead. - Forgetting that
teestill prints to stdout, so redirecting that output too can cause confusing double-writes. - Not knowing
teecan write to multiple files at once by listing several filenames.
tee filewrites stdin to bothfileand stdout simultaneously.tee -a fileappends instead of overwriting.teecan take multiple filenames to duplicate output into several files at once.teeis useful mid-pipeline to inspect data without breaking the pipe.
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first:
- Function Basics
- The read Command and Here-Strings
- Function Arguments
- stdin, stdout, stderr and File Descriptors
- Return Values
- Redirection Operators
- Local Variables
- Pipes and Chaining Commands
- Recursive Functions
- Here-Documents (<<EOF)
- Function Libraries
- The tee Command
- Discarding Output with /dev/null