🎓 A1Learner
🔍
0 of 46 lessons completed

Bash Tee and Streams

Tee copies a stream to a file and passes it onward. One copy lands in the file, and the other copy continues to the screen or down the pipeline.

Tee shows a line and saves it

The first line is tee printing to the screen. The second line is cat printing the saved file, and the two lines match.

echo "hello tee" | tee copy.txt
cat copy.txt

tee -a adds without erasing

The file already holds a first line. The appended line appears on the screen and then at the end of the file.

printf "first line\n" > log.txt
echo "second line" | tee -a log.txt
cat log.txt

Output and errors go to separate files

The block prints one line on each stream. The first printed line comes from the output file, and the second comes from the error file.

{
echo "standard line"
echo "error line" >&2
} > out.txt 2> err.txt
cat out.txt
cat err.txt

Example

printf "alpha\nbeta\ngamma\n" | tee lines.txt | grep "beta"
cat lines.txt

Key points

  • tee: a command that writes its input to a file and also prints it.
  • tee -a: the append form, which adds to a file instead of replacing it.
  • A pipeline after tee still receives the full input.
  • Separate files: redirect output to one file and errors to another to keep them apart.
  • tee reads standard input, so it sits in the middle of a pipeline.

In this example, printf sends three lines into tee. Tee saves all three lines in the file and passes them on to grep. Grep prints only the matching line, and then cat prints the full saved file.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does tee -a do?