Where to start First steps track · 15 stages
Linux Labs

tee — output to a file and the screen

3 min GNU coreutils

Splits a stream: writes to a file AND shows it on screen; sudo tee to write into protected files.

Cheat sheet

4 commands Printable version
  • cmd | tee file show and write (truncates the file)
  • cmd | tee -a file append
  • echo x | sudo tee -a /etc/f >/dev/null write into a protected file
  • cmd 2>&1 | tee log including stderr

Overview

tee reads stdin and writes it simultaneously to file(s) and to stdout. Useful when you need to both keep the output and see it, and when you need to write to a file through sudo (the > redirection doesn't carry sudo's privileges).

Options

2

Without -a, tee truncates the file to zero before writing — for logs and configs that get appended to rather than recreated, -a is always needed. -i makes tee ignore SIGINT (Ctrl+C), so an interrupt doesn't stop the write before the command itself finishes in the pipeline.

Option What it does Example
-a --append Append to the file instead of truncating it first. echo "line" | sudo tee -a /etc/hosts >/dev/null
-i --ignore-interrupts Ignore SIGINT (Ctrl+C) so an interrupt does not cut off the write early. long_command | tee -i log.txt

Nothing found. Try a shorter query.

Recipes

2

Examples

bash
make 2>&1 | tee build.log         # watch the build AND save the whole output
ls -l | tee files.txt             # show and write
echo "127.0.0.1 host" | sudo tee -a /etc/hosts   # -a: APPEND (to a protected file)
command | tee a.txt b.txt         # into several files at once
command | tee /dev/null           # "eat" stdout but get the exit code for pipefail

Why sudo tee

This is the main reason to know tee. The shell performs redirection BEFORE sudo, so you can't write to a system file this way:

bash
sudo echo "line" > /etc/file      # wrong: '>' opens the file as your own user
echo "line" | sudo tee -a /etc/file >/dev/null   # right: sudo tee does the writing

The trailing >/dev/null avoids duplicating the output on screen (we only need the write).

Troubleshooting

3

tee overwrote the file instead of appending

Without -a, tee truncates the file. Always use -a for logs/configs.

The exit code is always 0, even though the command failed

In a cmd | tee pipeline, the exit code comes from the last command (tee). Enable set -o pipefail (bash) to see cmd fail — see bash-scripting.

Writing to a root-owned file fails

Use | sudo tee, not sudo cmd >. See the "Why sudo tee" section and sudo.

See also

  • files-basics — Navigation and files — ls, cd, cp, mv, rm, cat, less, head, tail, copy-paste in the terminal.
  • sudo — Running commands as root or another user; sudoers and NOPASSWD.
  • text-tools — Text and stream processing — sorting, uniqueness, columns, counting.
Loading…