tee
Split a stream — show it on screen and write it to a file at the same time, including under sudo
tee reads standard input and writes it to two places at once: standard output and one or more files. Like a T-shaped pipe fitting: the stream continues down the pipeline, and a copy stays in the file.
Syntax
command | tee [options] [file…] [| next command]
Without files, tee just passes the input on. Files are created if they don't exist.
Options
| Option | What it does |
|---|---|
-a | append to the end of the files instead of overwriting |
-i | ignore the SIGINT interrupt signal (Ctrl+C) |
-p | don't die if the reading side of the pipeline has closed (e.g. | head): the files are still written to the end |
--output-error=mode | how to behave on a write error: warn, warn-nopipe (this is how -p works), exit, exit-nopipe |
By default, if the command to the right of tee closes the pipe, tee exits immediately — and only part of the data reaches the file.
Exit code — 0 if all writes succeeded; 1 if at least one file couldn't be opened or written (the others are still written).
Examples
# see the output and save it
ls -l /etc | tee listing.txt | head -n 3
# write to several files at once
echo 'hello' | tee a.txt b.txt
# append to the end without showing anything on screen
echo 'one more line' | tee -a a.txt > /dev/null
# save an intermediate pipeline result and keep processing
sort /etc/passwd | tee sorted.txt | wc -l
# save errors too: redirect stderr to stdout before tee
ls /etc /nonexistent 2>&1 | tee out.txt | head -n 2
# write to a file the current user has no permission for
echo 'option=1' | sudo tee /etc/example.conf > /dev/null
echo 'option=2' | sudo tee -a /etc/example.conf > /dev/null
# multi-line text into a file via a heredoc
tee notes.txt > /dev/null <<'EOF'
first line
second line
EOF
# the file gets everything, even though head reads only the first line
seq 100000 | tee -p all.txt | head -n 1
wc -l all.txt
# write to a file and compute a checksum at the same time
echo 'data' | tee copy.txt | sha256sum
Pitfalls
sudo echo … > /etc/filewon't work: the>redirection is done by your shell, without root. Run the process that writes under sudo:… | sudo tee /etc/file.- Without
-athe file is overwritten.teetruncates the file on start, like>. teealso prints to the screen. If you only need the write, add> /dev/null.- stderr doesn't reach
tee. A pipe|passes only stdout; to save errors too, write2>&1before|. More in Redirection. - A pipeline's exit code comes from the last command.
false | tee x.txtreturns 0, and the first command's error is lost. Enableset -o pipefail— see exit codes. … | tee file | headmay leave the file incomplete: whenheadfinishes,teegets SIGPIPE and exits. Add-p.- Don't write to a file you're currently reading.
cat f | tee fusually leavesfempty:teetruncates it beforecatmanages to read it.