The tee command in Linux is a useful utility that reads from standard input (stdin) and writes simultaneously to standard output (stdout) and one or more files. This makes it particularly useful for logging, debugging, and processing data in pipelines.


Basic Syntax of <strong>tee</strong> Command

command | tee [options] [file(s)]
  • command: The command whose output is to be captured.
  • file(s): One or more files where the output will be saved.
  • options: Additional flags that modify the behavior of tee.

Using <strong>tee</strong> to Write Output to a File

To save the output of a command to a file while still displaying it in the terminal, use:

ls -l | tee output.txt

This command lists files in the current directory and writes the output to output.txt while also displaying it on the screen.


Appending to a File with <strong>-a</strong> Option

By default, tee overwrites the file. To append instead, use the -a option:

echo "New log entry" | tee -a log.txt

This adds the new entry at the end of log.txt without deleting existing content.


Writing to Multiple Files

tee allows writing output to multiple files simultaneously:

uname -a | tee file1.txt file2.txt

The system information will be saved in both file1.txt and file2.txt.


Suppressing Output with <strong>/dev/null</strong>

To discard the output while writing it to a file:

ls -l | tee output.txt > /dev/null

This writes to output.txt but prevents output from appearing on the screen.


Using <strong>tee</strong> with Sudo for Protected Files

If you need to write to a file requiring root privileges:

echo "127.0.0.1 example.com" | sudo tee -a /etc/hosts

Unlike direct redirection (>>), this method ensures that the command runs with elevated privileges.


Using <strong>tee</strong> in Pipelines

tee is useful in complex shell pipelines, allowing inspection of intermediate results:

df -h | tee disk_usage.txt | grep '/dev/sda1'

Here, disk usage information is written to disk_usage.txt and filtered for /dev/sda1.


Ignoring Interrupt Signals with <strong>-i</strong> Option

To prevent interruption from keyboard signals (Ctrl+C), use:

echo "Logging data" | tee -i logfile.txt

This ensures that tee continues writing despite interruptions.


Conclusion

The tee command is a powerful tool for logging, debugging, and managing command output. Whether used for appending logs, handling permissions, or inspecting pipeline results, tee enhances script flexibility and efficiency.

Try these examples in your Linux terminal to understand how tee can optimize your workflow!