tee
Command in Linux: Redirecting Output to Multiple Destinations
Summary
The tee
command in Linux allows you to simultaneously display output to the terminal and save it to a file. It's a powerful tool for logging command output, auditing, and debugging, providing real-time visibility while preserving the data for later analysis.
Introduction
The tee
command is a simple yet invaluable utility that reads from standard input and writes to both standard output and one or more files. Think of it as a "T" splitter for your command output. This is extremely useful when you need to see the output of a command on your screen while also storing it in a file for record-keeping, troubleshooting, or further processing.
Use case and Examples
Basic Usage: Display output and save to file
This command lists the contents of the current directory usingls -l
and pipes the output to tee
. tee
then displays the output in your terminal and simultaneously saves it to a file named output.txt
. If output.txt
already exists, it will be overwritten. Appending to an Existing File
This command gets the current date and pipes the output totee
. The -a
option tells tee
to append the output to output.txt
instead of overwriting it. This is useful for building log files over time. Sending Output to Multiple Files
This command shows the currently logged-in users usingwho
. The output is then sent to both users.txt
and online.txt
. Each file will contain the same information. Suppressing Standard Output
Sometimes you only want to save the output to a file and not display it on the terminal. Redirecting the standard output to/dev/null
accomplishes this. Using with sudo
Running commands withsudo
often requires logging for security or auditing. This saves the output of the apt update
command to apt_update.log
, allowing review of the update process later. Commonly used flags
Flag | Description | Example |
---|---|---|
-a , --append | Append to the given files, do not overwrite. | command | tee -a logfile.txt (Appends the output of command to logfile.txt ) |
-i , --ignore-interrupts | Ignore interrupt signals. | command | tee -i logfile.txt (Prevents tee from being interrupted by Ctrl+C) |
-p | Diagnose errors writing to non pipes. | command | tee -p logfile.txt (tee will show if there are errors writing to logfile.txt) |
--output-error[=mode] | set behavior on write error; see below | command | tee --output-error=warn logfile.txt (sets write error behaviour) |
--help | Display help message and exit. | tee --help |
--version | Output version information and exit. | tee --version |