Command Line
File Processing
Stdout
Output Redirection
Scripting
How to redirect output to a file and stdout
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
The tee command in Unix/Linux reads from standard input and writes to both standard output and one or more files simultaneously. This is essential when you want to see command output in the terminal while also saving it to a log file. Without tee, you can only redirect to a file (>) or display on screen, but not both at once.
Basic Usage with tee
Append Instead of Overwrite
By default, tee overwrites the file. Use -a to append:
Write to Multiple Files
tee can write to multiple files simultaneously:
Redirecting Both stdout and stderr
tee only captures stdout by default. To capture stderr too:
Explanation of 2>&1
Redirect Only stderr
Using tee with sudo
Write to a file that requires root permissions:
Suppress tee's Terminal Output
If you only want the file and not the screen output:
Practical Examples
Build Logs
Long-Running Scripts
Pipeline Debugging
Inspect intermediate data in a pipeline:
SSH Session Logging
Alternatives to tee
Script Command (Record Full Sessions)
Process Substitution (Bash)
Redirecting in Background Scripts
Comparison of Redirect Methods
| Method | Screen | File | Append | stderr | |
> file | No | Yes | No | No | |
>> file | No | Yes | Yes | No | |
| `\ | tee file` | Yes | Yes | No | No |
| `\ | tee -a file` | Yes | Yes | Yes | No |
| `2>&1 \ | tee file` | Yes | Yes | No | Yes |
> >(tee file) 2>&1 | Yes | Yes | No | Yes |
Common Pitfalls
- Buffering: Output piped through
teemay be buffered, causing delayed display. Useunbuffer command | tee file(fromexpectpackage) orstdbuf -oL command | tee fileto force line-buffered output. - Exit codes: In a pipeline
command | tee file, the exit code is fromtee(usually 0), not fromcommand. Useset -o pipefailin bash to get the first non-zero exit code, or check${PIPESTATUS[0]}. - File permissions:
teecreates files with your user's permissions. Usesudo teeto write to root-owned files, notsudo command > file(the redirect runs as your user). - Binary data:
teeis designed for text. Binary data piped throughteemay be corrupted on some systems due to newline translation. - Disk space: Forgetting
-a(append) overwrites the file each time. Conversely, always appending without rotation can fill up the disk.
Summary
- Use
command | tee fileto display output on screen and save to a file simultaneously - Use
tee -a fileto append instead of overwrite - Use
command 2>&1 | tee fileto capture both stdout and stderr - Use
echo "text" | sudo tee /path/to/fileto write to root-owned files - Use
stdbuf -oLorunbufferto fix buffering issues with piped output

