How to Use the tee Command in Linux for Simultaneous Output and File Writing

The tee command is a built-in utility in Linux that reads input from standard input (STDIN) and writes it both to standard output (STDOUT) and to one or more specified files. It integrates efficiently with other commands via piping, providing customizable and versatile workflows. Unlike output redirection, tee allows users to observe command output in real-time, which is particularly beneficial for tasks such as logging and debugging within pipelines.

This guide will demonstrate how to leverage the tee command for writing and managing data with various options.

Syntax of the tee Command

The standard syntax for the tee command is as follows:

$ tee [OPTIONS]... [FILE]...

In this format, OPTIONS allow you to adjust the behavior of the command, while FILE defines the destination file(s) where the input should be saved. Below is a list of common options you can use with tee:

  • -a or --append: Adds the output to the end of the file instead of overwriting existing content.
  • -i or --ignore-interrupts: Prevents the command from being interrupted by signals.
  • -h or --help: Shows usage instructions and available options.
  • -v or --version: Displays the current version of the tee command.

To explore basic usage, try the examples below on your Linux machine.

Example: Display Help Information for the tee Command

Expected output:

Usage: tee [OPTION]... [FILE]...  
Copy standard input to each FILE, and also to standard output.  

  -a, --append              append to the given FILEs, do not overwrite  
  -i, --ignore-interrupts   ignore interrupt signals  
  -p                        diagnose errors writing to non pipes  
  --output-error[=MODE]     set behavior on write error. See MODE below  
  --help                    display this help and exit  
  --version                 output version information and exit

Example: Check the Installed Version of tee

Sample output:

tee (GNU coreutils) 8.30
Copyright (C) 2018 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Using the -i Option to Handle Interrupt Signals

Use the -i flag with the tee command to ensure it continues running even when an interrupt signal (like Ctrl + C) is sent:

This option is especially helpful for long-running processes to avoid disruptions. To terminate the tee process while using -i, press Ctrl + Z.

Create New Files Using the tee Command in Linux

The tee command is useful for both creating and modifying files. When used with the -a (append) option, it updates existing files without erasing their contents. If run without any options, tee will overwrite the target file. Below are steps for creating files using tee on a Linux system.

Generate a new file named output.txt and populate it with the text “Hello World” using tee:

$ echo "Hello World" | tee output.txt

Expected output:

Use the cat command to review the contents of the output.txt file and confirm that it includes the expected string:

Output:

Now, create another file named merged.txt using the data from output.txt:

$ cat output.txt | tee merged.txt

Output:

How to Overwrite Files Using the tee Command

The tee utility also enables overwriting existing files. By default, if no append option is used, tee replaces the current contents of the file. Use the following steps to overwrite a file using tee:

Check that output.txt still contains the original “Hello World” string:

Output:

Now, use the tee command to overwrite output.txt with a new message:

$ echo "Greetings" | tee output.txt

Expected output:

Finally, verify the updated content of output.txt:

Output:

 

Appending Content to Files with the tee Command

To add new data to an existing file without replacing its current content, use the tee command with the -a (append) option. Follow these instructions to append content to a file using tee.

Add the string “Hello” to the end of the output.txt file:

$ echo "Hello" | tee -a output.txt

Output:

Check the contents of output.txt to ensure the new line was added:

Output:

Writing to Multiple Files Using the tee Command

The tee command supports writing identical content to several files at once. This is especially useful when you want to log the same output in different locations while also displaying it in your terminal.

To write the same data to more than one file, list each filename as an argument:

$ tee <filename> <filename2> <filename3> ...

For example, to create two files with the same message, use the command below:

$ echo "The Data Backup Process is Complete" | tee file1.txt file2.txt

Review the content of both files to verify the data was written successfully:

Output:

The Data Backup Process is Complete
The Data Backup Process is Complete

This confirms that tee duplicated the string to both file1.txt and file2.txt. You can use the command to create, update, or append content across multiple files.

Writing Multi-Line Content to Multiple Files Using tee and Heredoc

To write several lines of text into multiple files at once, combine the tee command with a heredoc syntax. Here’s how to do it:

$ tee test1.txt test2.txt <<EOF
Backup Report - File 1 and File 2
2024 Backup Summary
EOF

The <<EOF syntax allows you to define multi-line input that tee writes to both test1.txt and test2.txt.

Verify the results by checking the contents of the newly written files:

Output:

Backup Report - File 1 and File 2
2024 Backup Summary
Backup Report - File 1 and File 2
2024 Backup Summary

Using the tee Command with Elevated (sudo) Permissions

To modify files that are owned by the root user or require administrative access, you must run the tee command with sudo. Follow the example below to append data to a system-level file using tee with elevated privileges.

Add the following line to the /etc/hosts file with root permissions:

$ echo "192.0.2.1 mycustomhost.local" | sudo tee -a /etc/hosts

This command adds the entry 192.0.2.1 mycustomhost.local to the /etc/hosts file. Since the file is owned by root, using sudo is necessary. Without it, the system will return a “permission denied” error.

Output:

192.0.2.1 mycustomhost.local

Confirm the change by inspecting the /etc/hosts file:

Your output should include:

127.0.0.1 localhost
...
::1 localhost ip6-localhost ip6-loopback
...

192.0.2.1 mycustomhost.local

Combining tee with Other Commands for Output Filtering and Redirection

The tee utility can be combined with other Linux commands in pipelines, allowing you to both display and store intermediate or final output. This is helpful when you need to filter, redirect, or save the results of a process. Explore the following examples for common usage patterns.

Redirect ls Output to a File

Run the ls command and use tee to write the results into a file named list.txt:

Review the contents of list.txt to confirm the operation:

Sample output:

file1.txt
file2.txt
list.txt
output.txt
test1.txt
test2.txt

Filter Output Using grep and Redirect with tee

You can insert grep between tee and another redirection to isolate specific output. Here’s how to find files ending in .txt and save them:

$ ls | tee intermediate.txt | grep .txt > final.txt

This command saves the output of ls to intermediate.txt. Then grep filters lines with .txt, and the final result is saved to final.txt.

Check both files to verify the results:

$ cat intermediate.txt
$ cat final.txt

Expected output:

final.txt
intermediate.txt
list.txt
merged.txt
output.txt

Advanced Filtering with awk and sort

Use tee alongside awk and sort to process command output. The following example captures a list of active processes and writes the sorted data to a file:

$ ps aux | tee process_list.txt | awk '{print $1, $2}' | sort | tee sorted_process_list.txt

This command saves the full process list in process_list.txt, filters the output to display only the username and PID, sorts the result, and writes it to sorted_process_list.txt.

Review both files to ensure the data is saved as expected:

$ cat process_list.txt
$ cat sorted_process_list.txt

Conclusion

In this guide, you explored the different ways to use the tee command in Linux—from basic file creation to advanced piping and filtering. By incorporating tee into your command-line workflows, you can create, overwrite, append, and log outputs effectively. For additional details, use the command below to view the manual:

Source: vultr.com

Create a Free Account

Register now and get access to our Cloud Services.

Posts you might be interested in:

Moderne Hosting Services mit Cloud Server, Managed Server und skalierbarem Cloud Hosting für professionelle IT-Infrastrukturen

Apache Airflow on Ubuntu 24.04 with Nginx and SSL

Apache, Tutorial

This guide provides step-by-step instructions for installing and configuring the Cohere Toolkit on Ubuntu 24.04. It includes environment preparation, dependency setup, and key commands to run language models and implement Retrieval-Augmented Generation (RAG) workflows. Ideal for developers building AI applications or integrating large language models into their existing projects.

Moderne Hosting Services mit Cloud Server, Managed Server und skalierbarem Cloud Hosting für professionelle IT-Infrastrukturen

Install Ruby on Rails on Debian 12 – Complete Guide

This guide provides step-by-step instructions for installing and configuring the Cohere Toolkit on Ubuntu 24.04. It includes environment preparation, dependency setup, and key commands to run language models and implement Retrieval-Augmented Generation (RAG) workflows. Ideal for developers building AI applications or integrating large language models into their existing projects.

Moderne Hosting Services mit Cloud Server, Managed Server und skalierbarem Cloud Hosting für professionelle IT-Infrastrukturen

Install VeraCrypt on Ubuntu 24.04 for Secure Encryption

Security, Tutorial

This guide provides step-by-step instructions for installing and configuring the Cohere Toolkit on Ubuntu 24.04. It includes environment preparation, dependency setup, and key commands to run language models and implement Retrieval-Augmented Generation (RAG) workflows. Ideal for developers building AI applications or integrating large language models into their existing projects.