How to Use tee in Bash: Syntax and Examples
In bash,
tee reads from standard input and writes the output to both a file and standard output. Use it by piping a command's output to tee filename to save and display the output at the same time.Syntax
The basic syntax of tee is:
command | tee [options] filename
Here, command is any command whose output you want to capture.
tee writes the output to filename and also sends it to the screen.
Common options include -a to append to the file instead of overwriting it.
bash
command | tee filename command | tee -a filename
Example
This example shows how to list files and save the output to files.txt while also displaying it on the screen.
bash
ls -l | tee files.txt
Output
total 8
-rw-r--r-- 1 user user 0 Apr 27 12:00 files.txt
-rw-r--r-- 1 user user 123 Apr 27 11:59 example.sh
Common Pitfalls
One common mistake is forgetting that tee overwrites files by default, which can cause data loss.
Use -a to append instead.
Also, tee only captures standard output, so errors sent to standard error won't be saved unless redirected.
bash
echo "Hello" > file.txt # Overwrites file.txt echo "World" | tee file.txt # Overwrites file.txt echo "Again" | tee -a file.txt # Appends to file.txt # To capture errors: command 2>&1 | tee output.log
Quick Reference
| Option | Description |
|---|---|
| filename | File to write output to |
| -a | Append output to the file instead of overwriting |
| -i | Ignore interrupt signals |
| -p | Force output to the terminal even if stdout is redirected |
Key Takeaways
Use
tee to save command output to a file and display it simultaneously.By default,
tee overwrites files; use -a to append instead.tee captures standard output only; redirect standard error if needed.Combine
tee with pipes to log outputs in scripts easily.