0
0
Linux-cliHow-ToBeginner · 3 min read

How to Use tee Command in Linux: Syntax and Examples

The tee command in Linux reads standard input and writes it to both standard output and one or more files. It is useful when you want to save the output of a command to a file while still seeing it on the screen.
📐

Syntax

The basic syntax of the tee command is:

  • command | tee [options] filename

Here, command is any command whose output you want to capture.

Options:

  • -a: Append the output to the file instead of overwriting it.
  • -i: Ignore interrupt signals.

filename is the file where the output will be saved.

bash
command | tee filename
command | tee -a filename
💻

Example

This example shows how to list files in a directory, save the list to a file, and still see the output on the screen.

bash
ls -l | tee filelist.txt
Output
total 8 -rw-r--r-- 1 user user 0 Apr 27 10:00 filelist.txt -rw-r--r-- 1 user user 123 Apr 27 09:59 example.txt
⚠️

Common Pitfalls

One common mistake is forgetting to use tee when you want to save output but still see it. Another is not using the -a option when you want to add to an existing file, which causes the file to be overwritten.

Also, using sudo incorrectly with tee can cause permission errors.

bash
echo "Hello" > file.txt  # Overwrites file

echo "World" | tee file.txt  # Overwrites file

echo "World" | tee -a file.txt  # Appends to file

# Wrong: sudo echo "text" > /root/file.txt (permission denied)
# Right:
echo "text" | sudo tee /root/file.txt
📊

Quick Reference

OptionDescription
-aAppend output to the file instead of overwriting
-iIgnore interrupt signals
filenameFile to write the output to
command | tee filenameSave output to file and display on screen

Key Takeaways

Use tee to save command output to a file and display it simultaneously.
Use the -a option to append output instead of overwriting files.
When using sudo with tee, pipe the output to sudo tee to avoid permission errors.
Without tee, redirecting output with > overwrites files and does not show output on screen.
tee is useful in scripts and command pipelines for logging and monitoring output.