The tee Command

Ever want to see output on screen AND save it to a file? That's what tee does.

Basic Usage

Terminal
$ls | tee listing.txt
Documents Downloads projects (also saved to listing.txt)

The output appears on screen AND is written to the file.

Why "tee"?

It's named after a T-pipe in plumbing - it splits the flow in two directions:

       ┌──> screen (stdout)
stdin ─┤
       └──> file

Append Mode

By default, tee overwrites. Use -a to append:

Terminal
$echo 'log entry' | tee -a app.log
log entry (appended to app.log)

Multiple Files

Terminal
$ls | tee file1.txt file2.txt file3.txt
(output goes to screen and all three files)

In Pipelines

tee can be anywhere in a pipeline:

Terminal
$cat access.log | tee raw.txt | grep 'ERROR' | tee errors.txt | wc -l
47 (raw.txt has all lines, errors.txt has errors)

This saves intermediate results while continuing the pipeline.

Debug Pipelines

Insert tee debug.txt in a pipeline to capture intermediate output for debugging without breaking the flow.

With sudo

A common gotcha:

hljs bash
# This fails - redirection happens before sudo
sudo echo "text" > /etc/file    # Permission denied

# This works - tee runs as root
echo "text" | sudo tee /etc/file

# Suppress stdout (write silently)
echo "text" | sudo tee /etc/file > /dev/null

Why This Works

> is handled by your shell (as regular user). tee is a command that can run with sudo. So sudo tee can write to protected files.

Real-World Examples

Watch and Log

Terminal
$tail -f app.log | tee -a archive.log | grep --line-buffered 'ERROR'
(watch for errors while archiving everything)

Build with Logging

Terminal
$make 2>&1 | tee build.log
(see build output and save it)

Download and Show Progress

Terminal
$curl -s https://example.com/data | tee data.json | jq '.count'
42 (save response and extract count)

Write System Config

Terminal
$echo '127.0.0.1 myapp.local' | sudo tee -a /etc/hosts
127.0.0.1 myapp.local

Tee vs Redirection

Want to...Use
Save output onlycommand > file
See and save outputcommand | tee file
Append and seecommand | tee -a file
Write to root-owned filecommand | sudo tee file
Knowledge Check

How do you append to a log file while also seeing the output?

Quick Reference

CommandEffect
tee fileWrite to file and stdout
tee -a fileAppend to file and stdout
tee f1 f2Write to multiple files
sudo tee fileWrite to root-owned file
tee file > /dev/nullWrite to file only (suppress stdout)

Key Takeaways

  • tee splits output to screen and file
  • -a appends instead of overwriting
  • Use in pipelines to capture intermediate results
  • sudo tee writes to protected files when > can't
  • Name comes from T-shaped plumbing pipes

Congratulations! You've completed Chapter 5: Pipes and Redirection.

You now understand the core of Unix power - combining simple commands into complex workflows. This is the foundation everything else builds on.

Next chapter: File Permissions - understanding who can do what.