Linux tee command

Linux tee command

Linux tee Command – Write Output to File and Screen

The tee command in Linux is used to read from standard input (stdin) and write to both standard output (screen) and one or more files simultaneously. It is commonly used in combination with pipes (|) to save command output while still displaying it.

Syntax of tee

command | tee [OPTIONS] filename
  • command → The command whose output will be processed.
  • filename → The file where the output will be saved.

If multiple filenames are specified, tee writes to all of them.

Basic Usage of tee

1. Save Command Output to a File

ls -l | tee output.txt

This displays the output of ls -l on the terminal and saves it to output.txt.

2. Append Output to a File (-a)

By default, tee overwrites the file. To append instead:

ls -l | tee -a output.txt

Now, the new output is added to output.txt instead of replacing it.

3. Save Output to Multiple Files

ls -l | tee file1.txt file2.txt

This saves the output into both file1.txt and file2.txt.

4. Hide Output but Still Save to a File

To suppress output and only write to a file:

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

This saves ls -l output into output.txt without showing it on the screen.

Advanced tee Usage

5. Use tee with sudo to Write Protected Files

Normally, sudo command > file fails due to permission issues. tee solves this:

echo "Custom config" | sudo tee /etc/myconfig.conf

This writes "Custom config" into /etc/myconfig.conf with root permissions.

To append instead of overwriting:

echo "New entry" | sudo tee -a /etc/myconfig.conf

6. Combine tee with Other Commands

Monitor a Log File While Saving (tail -f)

tail -f /var/log/syslog | tee log_copy.txt

This continuously prints and saves new logs to log_copy.txt.

7. Store dmesg Output for System Logs

dmesg | tee boot.log

This captures the kernel boot messages and saves them.

8. Use tee in a Script

An example script that logs both terminal and file output:

#!/bin/bash echo "Starting backup..." | tee backup.log tar -czf backup.tar.gz /home/user | tee -a backup.log echo "Backup complete." | tee -a backup.log

Now, both the terminal and backup.log will show the progress.

Difference Between tee and > / >>

CommandPurpose
command > fileRedirects output to a file (overwrites).
command >> fileRedirects output to a file (appends).
`commandtee file`

Conclusion

The tee command is useful for logging, debugging, and saving output while still displaying it on the terminal. It is a powerful tool for system administrators and script automation.

Would you like additional details or SEO optimization? 🚀

Souy Soeng

Souy Soeng

Our website teaches and reads PHP, Framework Laravel, and how to download Admin template sample source code free. Thank you for being so supportive!

Github

Post a Comment

CAN FEEDBACK
close