Using tee to Save and Display Output
The tee command copies its standard input to one or more files and also passes it on to standard output. The name comes from the T-shaped pipe fitting in plumbing: the data flows in one end and leaves through two branches. With tee, you can watch a command's output on the screen and keep a copy in a file at the same time, or you can capture the data flowing through the middle of a pipeline without stopping it.
Unless noted otherwise, the examples run in an empty working folder.
Understanding the Concept
A redirection such as > out.txt sends output to a file, and the screen shows nothing. A pipe sends output to the next command. Neither one does both. When you need both a record and a live view, tee is the tool for the job.
The tee command reads standard input, writes every byte to each file named on its command line, and writes the same bytes to its own standard output. Its own standard output is then free to continue through another pipe, or to appear on the terminal if tee is the last command.
Syntax
command | tee [options] file [file ...]
The most useful options:
| Option | Meaning |
|---|---|
-a or --append | Add to the end of each file instead of replacing it. |
-i or --ignore-interrupts | Ignore the interrupt signal sent by Ctrl + C. |
-p | Behave better when writing to a pipe (see tee --help on your system). |
--output-error[=MODE] | Choose what happens when a write to an output fails. |
Basic Example
printf 'one\ntwo\nthree\n' | tee out.txt
echo "[file]"
cat out.txt
Output:
one
two
three
[file]
one
two
three
Understanding the Example
The printf command produced three lines. The tee command at the end of the pipeline wrote them to out.txt and also printed them, which is why the three lines appear before the marker [file]. The following cat then shows that the file received exactly the same text.
Overwriting and Appending
By default tee replaces the contents of its target files, just as > does. Running it twice leaves only the second run's text:
echo "first" | tee log.txt > /dev/null
echo "second" | tee log.txt > /dev/null
cat log.txt
Output:
second
In both commands, > /dev/null discards the copy that tee would have printed, so only the file is written. To keep earlier content, add the -a option:
echo "first" | tee log2.txt > /dev/null
echo "second" | tee -a log2.txt > /dev/null
cat log2.txt
Output:
first
second
The option -a plays the same role as >> does for a plain redirection.
Writing to Several Files
List more than one file, and tee writes the same data to each of them:
echo "hello" | tee a.txt b.txt > /dev/null
cat a.txt b.txt
Output:
hello
hello
Capturing the Middle of a Pipeline
Because tee passes its input along unchanged, it can sit between any two stages of a pipeline. It records the data at that point and lets the pipeline continue:
printf 'b\na\nc\n' | tee raw.txt | sort | tee sorted.txt | wc -l
echo "[raw]"
cat raw.txt
echo "[sorted]"
cat sorted.txt
Output:
3
[raw]
b
a
c
[sorted]
a
b
c
The final wc -l printed 3. The first tee saved the unsorted data, and the second saved the sorted data. This technique is useful when debugging a long pipeline: put a tee after the stage you do not trust and look at what was actually passing through.
Standard Error Is Not Copied
Like every pipe, the one feeding tee carries only standard output. Error messages go straight to the terminal and never reach the file:
ls out.txt nofile 2>/dev/null | tee ls.txt
echo "[ls.txt]"
cat ls.txt
Output:
out.txt
[ls.txt]
out.txt
Here the error was discarded with 2>/dev/null. To record the error text as well, merge the two streams before the pipe, as lesson 60 explained:
ls out.txt nofile 2>&1 | tee ls2.txt
echo "[ls2.txt]"
cat ls2.txt
Output:
ls: cannot access 'nofile': No such file or directory
out.txt
[ls2.txt]
ls: cannot access 'nofile': No such file or directory
out.txt
Logging a Script's Progress
A common use is a build or deployment script that prints progress on the screen and keeps a log file. With -a, repeated runs add to the same file:
echo "build started" | tee -a build.log
echo "build ok" | tee -a build.log
echo "[build.log]"
cat build.log
Output:
build started
build ok
[build.log]
build started
build ok
For a script that produces a lot of output, you can pipe an entire command or function through tee, as in ./deploy.sh 2>&1 | tee -a deploy.log.
Writing to Protected Files
A redirection is set up by the shell before the command starts, using the privileges of the person running the shell. This matters when a file needs elevated permission. Using sudo in front of the command does not help the redirection, because only the command gets elevated privileges:
sudo echo "data" > /etc/protected.conf
The shell opens /etc/protected.conf for writing before sudo runs, so the write fails with a permission error. Because tee opens its own files, running tee itself with sudo solves the problem:
echo "data" | sudo tee /etc/protected.conf > /dev/null
The sample commands above were written for explanation and were not run in the sandbox that tested this lesson. The same difference between a redirection and tee was tested here with a read-only folder, using an unprivileged user:
echo data | tee ro/x.txt
echo "status: $?"
echo data > ro/y.txt
echo "redirect status: $?"
Output:
tee: ro/x.txt: Permission denied
data
status: 1
nobody_test.sh: line 4: ro/y.txt: Permission denied
redirect status: 1
Both attempts failed with the same permission error, and both returned status 1. Notice one detail: tee still printed data on its standard output, because failing to open one file does not stop it from copying to the others and to the screen. Lines such as nobody_test.sh: line 4: come from running the commands in a script; typed interactively, the message begins with bash:.
Exit Status and Write Errors
The tee command returns status 0 when every write succeeded and a non-zero status when it could not write to one of its files:
echo hi | tee /nonexistent/dir/file > /dev/null
echo "status: $?"
Output:
tee: /nonexistent/dir/file: No such file or directory
status: 1
Even in this failing case, with the error message hidden by 2>/dev/null, the line hi is still copied to standard output:
echo hi | tee /nonexistent/dir/file 2>/dev/null
echo "status: $?"
Output:
hi
status: 1
If tee is not the last command in a pipeline, its failure is hidden by default, because a pipeline reports only the last command's status. With set -o pipefail, a failure anywhere in the pipeline becomes the pipeline's status:
set -o pipefail
false | tee x.txt > /dev/null
echo "pipefail status: $?"
set +o pipefail
Output:
pipefail status: 1
Splitting a Stream with Process Substitution
The file arguments of tee can be process substitutions, which look like file names but are connected to other commands. This sends one stream to a file and to a second command at the same time:
printf 'x\ny\nz\n' | tee >(wc -l > count.txt) > all.txt
sleep 0.2
echo "count: $(cat count.txt)"
echo "all:"
cat all.txt
Output:
count: 3
all:
x
y
z
The >(...) part starts wc -l as a separate process and gives tee a file name that feeds its standard input. The short sleep gives that background process time to finish writing count.txt before it is read. Process substitution is a Bash feature, covered in detail in lesson 151.
Using tee with Special Files
Special files such as /dev/stderr can be used as targets. This copies the data to standard error and discards the normal copy:
echo "debug" | tee /dev/stderr > /dev/null 2>err.txt
cat err.txt
Output:
debug
The command substitution below shows a practical use. It captures the output of a pipeline in a variable while also showing the data on the screen through standard error:
res=$(printf 'a\nb\n' | tee /dev/stderr | wc -l)
echo "res=$res"
Output:
a
b
res=2
The lines a and b reached the terminal through standard error, and the variable res received the count from wc.
Why tee Should Not Write to Its Own Input File
If tee writes to the same file that an earlier command in the pipeline is reading, both processes start at the same time. The tee command empties the file when it opens it, and the reader may or may not have read the data by then. The test below uses a small file:
printf 'keep\n' > same.txt
cat same.txt | tee same.txt > /dev/null
echo "size after: $(wc -c < same.txt)"
Output:
size after: 5
In this particular run, the file survived because cat finished reading it quickly and tee wrote the same text back. The outcome of such a command depends on timing, and with larger files or slower commands the data can be damaged. Write the result to a different file and rename it when the pipeline succeeds.