← Back to Bash Course | Chapter 8: Input/Output & Redirection | Lesson 12 of 13

The tee Command

The tee command copies text into a file while still letting it pass through to the screen or the next command, like a T-junction in a pipe.

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

bash
#!/bin/bash
echo "important result" | tee result.txt
echo "file contents:"
cat result.txt
rm -f result.txt

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

bash
#!/bin/bash
echo "first" | tee notes.txt > /dev/null
echo "second" | tee -a notes.txt > /dev/null
cat notes.txt
rm -f notes.txt

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

bash
#!/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

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

bash
#!/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
Common Mistakes
  1. Assuming tee always overwrites the file; by default it truncates, but tee -a is needed to append instead.
  2. Forgetting that tee still prints to stdout, so redirecting that output too can cause confusing double-writes.
  3. Not knowing tee can write to multiple files at once by listing several filenames.
Chapter Summary
  • tee file writes stdin to both file and stdout simultaneously.
  • tee -a file appends instead of overwriting.
  • tee can take multiple filenames to duplicate output into several files at once.
  • tee is useful mid-pipeline to inspect data without breaking the pipe.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.