Using tee to Save and Display Output

Su Suriya Ravichandran Updated 06 Dec 2026
8 min read ·Lesson 62 of 205

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:

OptionMeaning
-a or --appendAdd to the end of each file instead of replacing it.
-i or --ignore-interruptsIgnore the interrupt signal sent by Ctrl + C.
-pBehave 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.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Using tee to Save and Display Output and get answers drawn from it.

Signed-in readers only.