Website Vidya
Cloud & DevOpsStep-by-Step Guide

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.

RR
Rajesh RayLead Systems Educator
Published:
9 min read
PDF Cheat Sheet
tee Command in Linux: Split and Redirect Streams with Examples
AI Executive SummaryWebsiteVidya AI

9 min read

Learn tee command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

Key Highlights
  • What tee Does and When to Use It
  • Availability and Installation Across Linux Distributions
  • Command Syntax, Arguments, and Exit Status Codes
Grounded in full engineering runbookWebsiteVidya AI Engine

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.

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.

Advertisement
tee Command in Linux: Split and Redirect Streams with Examples — syntax, flags, and practical terminal workflow diagram
tee Command in Linux: Split and Redirect Streams with Examples — command syntax, key options, and production workflow reference.

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:

Advertisement

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 / FlagLong Form / ArgumentTechnical Behavior and Purpose
-a--appendAppend to the given files; do not overwrite existing contents.
-i--ignore-interruptsIgnore 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--helpDisplay help documentation and exit.
--version--versionOutput 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.

Advertisement

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

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

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
In bash, redirection operators (> and >>) are executed by your current shell before sudo is invoked. If your user account is unprivileged, the shell fails to open the root file. Piping to sudo tee runs tee itself as root, allowing it to open and write to the protected file.
Redirect stderr (file descriptor 2) to stdout (file descriptor 1) before piping to tee: command 2>&1 | tee output.log. In bash 4+, you can also use the shorthand: command |& tee output.log.
Yes. Simply list all destination files as arguments: command | tee file1.log file2.log file3.log. tee writes the identical stream to all three files and prints it on your terminal screen.
Redirect standard output to /dev/null: command | sudo tee /etc/file.conf > /dev/null. The file will be written, but nothing will be echoed to your terminal.
RR
Written byVerified Author

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.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Cloud & DevOps•

How to Close File Descriptors Above 9 in Dash Shell

Attempting to close a file descriptor above 9 in Dash using exec 10<&- results in a 10: not found error because Dash's POSIX lexer only recognizes single-digit file descriptors (0–9) in redirection operators. This guide explains the exact parser limitation, why FDs 10+ are reserved for internal shell state, and how to safely close inherited file descriptors using close_range, Python, or Perl wrappers.

RR
Rajesh Rai
Read More
Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout