tee Command in Linux: Split and Redirect Streams with Examples
Learn tee command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
9 min read
Learn tee command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
- What tee Does and When to Use It
- Availability and Installation Across Linux Distributions
- Command Syntax, Arguments, and Exit Status Codes
The tee command in linux is one of the most practical and frequently used stream utilities in the Unix ecosystem. Named after the T-shaped pipe splitter used in plumbing, tee reads data from standard input (file descriptor 0) and simultaneously duplicates that stream, writing one copy to standard output (file descriptor 1) and writing identical copies to every file specified on the command line.
The tee command in Linux reads from standard input and simultaneously writes to standard output and one or more files. It acts as a T-junction pipe splitter, allowing you to view command output in your terminal while logging it to disk (e.g. command | tee output.log) or write to root-owned files using sudo tee /path/to/file.
In daily system administration and automated operations, engineers frequently encounter situations where they must monitor long-running processes interactively while simultaneously persisting log records to disk for audit trails. Rather than running the command twice or relying on complex terminal multiplexing, tee solves this dilemma in a single, composable pipeline.
Furthermore, tee provides the definitive solution to the classic Linux permission trap: attempting to redirect output into a root-protected system file via sudo echo '...' > /etc/config fails because the redirection operator (>) is evaluated by the unprivileged shell before sudo executes. Piping to sudo tee bypasses this restriction cleanly and securely.
What tee Does and When to Use It
Architecturally, GNU coreutils tee is implemented as an efficient I/O multiplexer. Upon invocation, tee opens each target file passed in its argument vector using the open(2) system call with flags O_WRONLY | O_CREAT | (O_APPEND or O_TRUNC depending on whether -a is supplied). It stores these open file descriptors in a dynamically allocated array alongside standard output (fd 1).
tee then enters a tight read-write loop: it reads blocks of data (typically 8KB to 64KB) from stdin using read(2). For each successfully read block, tee iterates through its list of file descriptors, issuing write(2) calls to each target. If a downstream consumer in a pipeline closes its read end or terminates, the kernel dispatches a SIGPIPE signal. GNU tee allows fine-grained error control via -p (--output-error), letting scripts decide whether to terminate immediately or continue writing to surviving files.
Under the hood, tee gathers runtime telemetry or dispatches control signals by reading virtual filesystems mounted at /proc and /sys, or by communicating with PID 1 (systemd) over D-Bus. Using flags such as -a, -i, -p, --help turns raw process and service tables into actionable diagnostics during incident response.
Availability and Installation Across Linux Distributions
The tee utility is packaged in coreutils across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:
Before running administrative tasks or automation scripts, verify whether tee is installed and inspect which binary path and version your shell resolves:
type -a tee
tee --version 2>/dev/null || man -f tee
# Illustrative output (reviewed against documentation)
tee is /usr/bin/tee
tee (coreutils)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y coreutils
# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y coreutils
# Arch Linux
sudo pacman -S --noconfirm coreutils
# Alpine Linux
sudo apk add --no-cache coreutils
Command Syntax, Arguments, and Exit Status Codes
tee [OPTIONS] [FILE...]
The invocation syntax is straightforward: tee [OPTIONS] [FILE...]. Any number of target file paths can be supplied. If no FILE arguments are specified, tee simply acts as a passthrough filter, copying standard input directly to standard output.
By default, tee truncates (overwrites) existing destination files. Passing the -a (--append) flag changes the file opening mode to append, preserving historical log data. The -i (--ignore-interrupts) flag instructs tee to ignore SIGINT signals (such as Ctrl+C), ensuring file logging completes cleanly even if an interactive user interrupts terminal display.
0— Successful execution; standard input successfully copied to stdout and all files.1— Operational failure; unable to open or write to one or more destination files.2— Invalid command-line option syntax.
Important Options and Flags Reference
| Option / Flag | Long Form / Argument | Technical Behavior and Purpose |
|---|---|---|
-a | --append | Append to the given files; do not overwrite existing contents. |
-i | --ignore-interrupts | Ignore interrupt signals (SIGINT, e.g. Ctrl+C). |
-p | --output-error[=MODE] | Set error handling behavior upon write failure (warn, warn-nopipe, exit, exit-nopipe). |
--help | --help | Display help documentation and exit. |
--version | --version | Output version information and exit. |
The -a (--append) option is critical when tee is integrated into scheduled cron jobs or log rotation pipelines. Forgetting -a causes tee to truncate the target file, wiping out previous logs each time the script executes.
The -p option is particularly valuable in enterprise shell scripts. In complex pipelines like cmd | tee -p log.txt | grep 'alert', if grep exits early after finding a match, the default behavior might raise an error. Setting --output-error=warn-nopipe ensures tee ignores broken pipe errors on stdout while continuing to write the complete stream to log.txt.
When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.
Practical Basic and Advanced Usage Examples
1. Simultaneously Display Output and Log to a File
Run a system update while viewing progress in the terminal and saving full output to a log file.
sudo apt-get update | tee update.log | head -n 4
# Illustrative output (reviewed against documentation)
Hit:1 http://archive.ubuntu.com/ubuntu jammy InRelease
Get:2 http://security.ubuntu.com/ubuntu jammy-security InRelease [110 kB]
Get:3 http://archive.ubuntu.com/ubuntu jammy-updates InRelease [119 kB]
Fetched 229 kB in 1s (245 kB/s)
tee writes each line of apt output to update.log while concurrently forwarding it to the terminal.
2. Append Output to an Existing Log File with -a
Append diagnostic ping results to a continuous network connectivity log without overwriting.
ping -c 2 8.8.8.8 | tee -a network.log
# Illustrative output (reviewed against documentation)
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=118 time=12.4 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=118 time=12.1 ms
--- 8.8.8.8 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1002ms
The -a flag appends the new ping records to network.log, preserving all existing entries.
3. Write to Privileged Root Files with sudo tee
Safely write kernel parameter directives into /etc/sysctl.d/ without opening an interactive root editor.
echo "net.ipv4.ip_forward = 1" | sudo tee /etc/sysctl.d/99-ipforward.conf
# Illustrative output (reviewed against documentation)
net.ipv4.ip_forward = 1
Because sudo runs tee with root privileges, tee can open and write to /etc/sysctl.d/ safely.
4. Suppress Terminal Output by Redirecting to /dev/null
Use sudo tee to update a system file silently without echoing the content back to stdout.
echo "nameserver 1.1.1.1" | sudo tee -a /etc/resolv.conf > /dev/null
# Illustrative output (reviewed against documentation)
# No terminal output emitted
Redirecting tee's stdout to /dev/null suppresses terminal output while still writing to the destination file.
5. Write to Multiple Files Simultaneously
Duplicate a configuration snippet or message across multiple backup directories at once.
echo "MAINTENANCE_MODE=true" | tee /opt/app1/.env /opt/app2/.env /opt/app3/.env
# Illustrative output (reviewed against documentation)
MAINTENANCE_MODE=true
tee accepts multiple file paths and writes the identical input stream to all of them in parallel.
6. Capture Intermediate Pipeline Output for Debugging
Inspect the raw unparsed data between pipeline stages without breaking the flow.
cat /etc/passwd | tee /tmp/raw_passwd.tmp | cut -d: -f1 | head -n 3
# Illustrative output (reviewed against documentation)
root
daemon
bin
Placing tee in the middle of a pipeline saves the intermediate stream to /tmp/raw_passwd.tmp for analysis.
Real-World Workflows, Pipelines, and Shell Automation
Automated Host Hardening: Writing Sysctl Baseline Parameters
Automate system kernel hardening by writing security configurations to protected directories via sudo tee.
#!/usr/bin/env bash
set -euo pipefail
echo "Applying network security hardening parameters..."
cat << 'EOF' | sudo tee /etc/sysctl.d/99-security-hardening.conf > /dev/null
# Disable ICMP redirect acceptance
net.ipv4.conf.all.accept_redirects = 0
net.ipv6.conf.all.accept_redirects = 0
# Enable TCP SYN cookies against flood attacks
net.ipv4.tcp_syncookies = 1
# Ignore ICMP echo broadcasts
net.ipv4.icmp_echo_ignore_broadcasts = 1
EOF
sudo sysctl -p /etc/sysctl.d/99-security-hardening.conf
# Illustrative output (reviewed against documentation)
Applying network security hardening parameters...
net.ipv4.conf.all.accept_redirects = 0
net.ipv6.conf.all.accept_redirects = 0
net.ipv4.tcp_syncookies = 1
net.ipv4.icmp_echo_ignore_broadcasts = 1
Using heredoc redirection into sudo tee > /dev/null provides a robust, non-interactive method for provisioning root-owned config files.
CI/CD Build Runner: Dual Console and Artifact Logging
Capture build execution output for web console inspection while saving artifact logs for compliance.
#!/usr/bin/env bash
set -euo pipefail
BUILD_LOG="/var/log/builds/build-$(date +%Y%m%d-%H%M%S).log"
mkdir -p "$(dirname "$BUILD_LOG")"
echo "=== Starting CI Build Phase ===" | tee "$BUILD_LOG"
# Run build tasks, capturing both stdout and stderr (2>&1)
{
echo "[STEP 1] Compiling binaries..."
sleep 1
echo "[STEP 2] Running unit test suite..."
sleep 1
echo "[SUCCESS] Build completed with 0 errors."
} 2>&1 | tee -a "$BUILD_LOG"
echo "Build log securely archived at: $BUILD_LOG"
# Illustrative output (reviewed against documentation)
=== Starting CI Build Phase ===
[STEP 1] Compiling binaries...
[STEP 2] Running unit test suite...
[SUCCESS] Build completed with 0 errors.
Build log securely archived at: /var/log/builds/build-20261022-153000.log
By combining 2>&1 with tee -a, the script guarantees both standard output and standard error are saved to the persistent log.
Pipelines, Redirection, Quoting, and Shell Expansion
When embedding tee inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.
Permissions, Security Implications, and Safe Execution
Invoking tee without the -a (--append) flag will immediately truncate and overwrite any specified target files without prompting for confirmation. Always double-check whether -a is required when writing to existing files.
Running sudo tee /path/to/file gives the tee process root privileges, allowing it to overwrite or create any file on the system, including critical files like /etc/shadow or /etc/sudoers. Ensure the data piped into sudo tee is strictly validated and cannot be manipulated by untrusted users.
When redirecting sensitive tokens or private keys using tee (e.g. cat id_rsa | tee backup.key), be aware that tee copies the data to stdout (your terminal screen and shell history/scrollback) in addition to the file. Redirect stdout to /dev/null to prevent credential leakage.
GNU/Linux, BSD, and BusyBox Implementation Differences
The basic options -a and -i are part of the POSIX standard and function identically across all Unix platforms, including GNU coreutils, BSD systems (macOS, FreeBSD), and BusyBox on Alpine Linux.
The -p (--output-error) flag is a GNU coreutils extension and is not supported by standard BSD tee or BusyBox tee. For universal portability across minimal container environments, avoid -p and handle pipe failures via shell options like set -o pipefail.
Troubleshooting Common Errors and Diagnostics
Permission denied when writing with sudo echo '...' > /etc/file
Root Cause: The shell performs redirection (>) under the unprivileged user's shell session before sudo executes the echo command.
Resolution: Pipe the echo output into sudo tee instead.
# Incorrect (fails with Permission denied):
# sudo echo "config" > /etc/protected.conf
# Correct:
echo "config" | sudo tee /etc/protected.conf
tee: write error: Broken pipe
Root Cause: A downstream command in the pipeline (such as head or grep -q) closed its standard input stream early after reading its required data.
Resolution: In GNU tee, use -p (--output-error=warn-nopipe) to ignore broken pipe signals on stdout.
cat /var/log/large.log | tee -p saved.log | head -n 5
Existing log file erased on rerun
Root Cause: tee was invoked without the -a (--append) flag, causing it to truncate the destination file to 0 bytes upon opening.
Resolution: Always include the -a flag when appending to logs.
echo "New log entry" | tee -a /var/log/app.log
Alternatives, Related Commands, and Related Tutorials
- Grep Command in Linux: Search Text, Files, and Directories — Practical syntax, flags, and examples for
grep. - awk Command in Linux: Syntax, Text Patterns, and Field Processing — Practical syntax, flags, and examples for
awk. - tr Command in Linux: Translate, Delete, and Squeeze Characters — Practical syntax, flags, and examples for
tr. - tail Command in Linux: Output End of Files and Follow Live Logs — Practical syntax, flags, and examples for
tail. - 25 Best Linux Commands Every Sysadmin Should Know — Core command-line utilities for daily Linux server administration.
- How to Find a File in Linux from the Command Line — Practical file search patterns across Linux directories.
- Linux Commands Knowledge Hub (#linux-commands) — Browse all Linux command-line tutorials and system administration references.
Authoritative References and Official Documentation

The Linux Command Line, 2nd Edition: A Complete Introduction
Frequently Asked Questions
Quick answers to common questions and configurations
/dev/null: command | sudo tee /etc/file.conf > /dev/null. The file will be written, but nothing will be echoed to your terminal.Editorial Disclosure: Website Vidya is supported by our readers. When you purchase hosting, tools, or software through our verified partner links, we may earn an affiliate commission at no extra cost to you. We only recommend solutions we trust and rigorously verify.
Rajesh Ray
I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.
Most Read Guides
TrendingUbuntu Server Not Booting? 10 Simple Steps to Fix It Fast
How to Create a 3D Button in HTML and CSS: Easy Steps
How to Install Python and Pip on Ubuntu 24.04 LTS
How to Install Nginx on Ubuntu 24.04
How to Install Python on Ubuntu 24.04 LTS
Related Technical Guides
Tested runbooks, server administration walkthroughs, and troubleshooting guides





Join the Conversation & Perspective
Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.
No comments on this guide yet. Be the first to share your thoughts or ask a question!