Mastering the Linux tee Command for Redirecting Output In 9 Examples

Try this guide with our instant dedicated server for as low as 40 Euros

tee command in linux

Redirection is a common action in Linux system management. Admins need to redirect the output of the commands and scripts to other files, display options, and other destinations. 

A critical problem with the traditional redirection is the single-track nature of these commands. These commands can only work with one destination. However, in many real-world scenarios, you might need to redirect output to two (or more destinations). 

The tee command in Linux is a versatile and powerful command used primarily for redirecting output to multiple destinations simultaneously. 

It is implemented as a T-shaped pipe, hence the name. In common applications of the command, you can capture a command’s output and simultaneously display it on the screen and redirect it to one or more files.

As you can imagine, this command simplifies critical system operations such as monitoring and logging, where you need to see the output of commands in real-time while saving it to a file for later analysis. In addition, it’s used in scripting, debugging, and other system administration tasks.

tee command tree

In this tutorial, we will take a close look at the tee command and discuss 9 use cases where this command proves invaluable. However, before this, we will go over the idea of redirection in Linux environments and how the various implementations of this idea help you achieve specific outcomes. 

Table Of Contents

  1. The Concept of Input/Output Redirection
    1. Input Redirection (<)
    2. Output Redirection (> and >>)
  2. The Difference Between tee, redirection, and pipe
    1. Redirection (> and >>)
    2. Piping (|)
    3. tee Command
  3. The tee Command Basic Syntax
  4. What Is the Linux Tee Command Used For?
  5. How Do I Install the Linux tee Command?
    1. Step #1: Check if the tee is Installed
    2. Step #2: Install the tee Utility (if it isn’t already)
    3. Step #3: Verify Installation
    4. Step #4: Additional Options
  6. Examples of tee Command in Linux
    1. The Prerequisites
    2. Example #1: Append to a File
    3. Example #2: Redirect the Output to Multiple Files
    4. Example #3: Combine tee with sudo
    5. Example #4: View and Save a Command’s Output
    6. Example #5: Piping Multiple Commands
    7. Example #6: Create Backup(s) and Update Logs
    8. Example #7: Monitor and Update Command Output
    9. Example #8: Filtering and Saving Output
    10. Example #9: Redirect the Standard Error (stderr)
  7. Fixing Frequently Occurring Common Issues
    1. Issue #1: Issues with Permission
    2. Issue #2: Overwriting Files
  8. Conclusion
  9. FAQs

The Concept of Input/Output Redirection

The concept of input/output (I/O) redirection in Linux refers to the ability to change the default sources and destinations of input and output streams for commands and programs. Put more simply, it allows you to decide where a command receives input and where it sends output. It is centered on controlling the two-way data flow between files, devices, and processes. 

Let’s look at the two components of this data flow process:

Input Redirection (<)

Input redirection allows you to take input from a file or device rather than the keyboard (the standard input).

The typical command syntax of input redirection is as follows:

command < input_file 

This syntax reads input from input_file instead of the keyboard for the command.

Output Redirection (> and >>)

With output redirection, you can direct a command’s output to a file or device rather than seeing it appear on the terminal. 

The output redirection is implemented in two similar ways:

> overwrites the contents of the target file while >> appends to the end of the file.

This is a critical distinction that affects how the command affects the output file.

The command syntax of both types of redirection is similar. 

  • command > output_file redirects the output of a command to output_file.
  • command >> output_file appends the output of a command to output_file.

The Difference Between tee, redirection, and pipe

Now that you know the idea of redirection, let’s see the three basic implementations of the idea – the tee command, redirection (> or >>) and piping (|) in Linux:

  • Redirection (> and >>)

    • Purpose: Redirection is used to send the output of a command to a file or device.
    • Functionality: The > operator overwrites the contents of a file with the output of a command while >> appends the output to the end of the file.
    • Example:

      # echo "Hello, World!" > output.txt

      This command redirects the echo “Hello, World!” output to output.txt, overwriting any existing content.
    • Limitation: Redirection only allows output to be directed to a single destination (file or device) and doesn’t display the output on the terminal.
  • Piping (|)

     

    • Purpose: The output of one command can be sent as input to another program using piping.
    • Functionality: The | operator connects one command’s standard output (stdout) to another command’s standard input (stdin).
    • Example:

      # ls -l | grep "file"

      This command lists files and directories in the current directory (ls -l) and pipes the output to grep, which filters the output to display lines containing the word file.
    • Limitation: Piping only allows output to flow sequentially from one command to another without saving it to a file or displaying it on the terminal.
  • tee Command

    • Purpose: tee is used to reroute output to several destinations simultaneously.
    • Functionality: tee takes one or more files as parameters, reads from the standard input, and writes to the standard output.
    • Example:
      # echo “Hello, World!” | tee output.txt

      This command displays “Hello, World!” on the terminal and saves it to output.txt simultaneously.
    • Advantages: tee allows output to be displayed on the terminal while saving it to one or more files, providing a way to monitor output in real-time and simultaneously create backups or logs.
    • Limitations: Unlike redirection and piping, tee doesn’t allow complex manipulation of output streams between commands. Instead, it simply duplicates the output at multiple locations.

The tee Command Basic Syntax

The tee command’s basic syntax is as follows:
# [command] | tee [options] [filename or file path]
For instance, consider the following command syntax:
# echo "Hello, World!" | tee output.txt

This command lists the contents of the current directory (ls -l) and simultaneously saves the output to a file named output.txt.

The tee Command Basic Syntax

Also Read: lsof Command in Linux with Examples

What Is the Linux Tee Command Used For?

Now that you know how the tee command works, it is important to to know the applications of the command:

  • Reads Input: tee reads data from the standard input, which can be provided through a pipeline or entered interactively.
  • Writes to Standard Output: tee writes the input data to the standard terminal output and displays the data on the terminal like any other command.
  • Writes to Files: tee also writes the input data to one or more files specified as arguments. These files can be newly created or existing. Note that the command will overwrite or append to these files, based on the options used.
  • Multiple Outputs: One of the key features of the tee is its ability to split the input stream and send it to multiple destinations simultaneously. This can be useful for logging, debugging, or any situation where you must capture or duplicate command output.
  • Options: tee supports several options that modify its behavior. These options can instruct the command to append to files (-a), ignore interrupt signals (-i), or specify file permissions (-p). These options can enhance its functionality and provide more control over the output.

How Do I Install the Linux tee Command?

Since tee is part of the GNU Coreutils package, chances are that the utility is available in most Linux distributions. 

However, if you find that your system does not have the utility, you can easily install or reinstall the utility by following these steps.

Step #1: Check if the tee is Installed

Start by checking if tee is installed on your system by running the following command in your terminal:

# which tee
If the utility is installed, this command will display its location (typically /usr/bin/tee). Alternatively, if nothing is displayed, the tee may not be installed.

Step #2: Install the tee Utility (if it isn’t already)

We recommend using the package manager of your Linux distribution to install the utility if it hasn’t already been installed.. Since distributions have different package managers, we will present the following two commands that use the package manager of your distribution to install the utility on your system:

Debian/Ubuntu

# sudo apt-get install coreutils

Red Hat/CentOS

# sudo yum install coreutils

Step #3: Verify Installation

After installing tee, run the first step again to confirm its installation.

Step #4: Additional Options 

After installing the utility, we recommend checking the official manual to explore available options. For this, run the following command:

# man tee

This command will display the tee’s manual page, providing a detailed guide on its usage and available options.

Examples of tee Command in Linux

At this point, you know the theoretical aspects of the tee utility, let’s explore the application of this utility.

The Prerequisites

Before you try out the examples in this tutorial, make sure you have the following:

  • A system running a mainstream Linux distribution
  • A user account with root or sudo privileges
  • Access to the command line or terminal

Example #1: Append to a File

Consider the following command that adds a line of text to a file and routes it to the echo command:

# echo "New line" | tee -a output.txt

As you can see, the command appends the text New line to the file output.txt, while also displaying it on the terminal.

Append to a File

Finally, we used the cat command to verify the contents of the output.txt file.

Example #2: Redirect the Output to Multiple Files

Consider the following scenario where we used the ps aux command to list all running processes. We used the tee to simultaneously save the output to two files: processes.txt and users.txt.

# ps aux | tee processes.txt users.txt

Redirect the Output to Multiple Files

Example #3: Combine tee with sudo

It is common to see the tee command with commands that require escalated privileges. That’s why you can easily combine the tee command with sudo to run critical commands. Here’s an example where we used sudo to run dmesg<span style=”font-weight: 400;”>, a critical utility that prints kernel messages.

# sudo dmesg | tee dmesg_output.txt

Combine tee with sudo

As you can see, the command retrieves kernel messages using dmesg with elevated privileges provided by sudo and saves the output to a file named dmesg_output.txt.

Example #4: View and Save a Command’s Output

Perhaps, the most typical usage of the tee command is to simultaneously view the output of a command on the stdout and save it to a local file. 

Consider the following command that displays the contents of the /etc/passwd file (the user account information) and simultaneously saves it to a file called user_list.txt.

# cat /etc/passwd | tee user_list.txt

View and Save a Command’s Output

Example #5: Piping Multiple Commands

Let’s combine the tee command with pipes to show how you can build complex command pipelines and execute multiple operations in a single command. 

For instance, consider the following scenario where we used tee to redirect the output of two grep commands to two different files. 

The echo command prints Hello, World! to the screen, and then tee filters and saves the lines containing Hello to hello.txt and the lines containing World to world.txt using the pipe symbol (|).
#echo "Hello, World!" | tee >(grep World > world.txt) >(grep Hello > hello.txt)

We can verify the outcome by using the cat command to display the contents of both files:

Piping Multiple Commands

Example #6: Create Backup(s) and Update Logs

You can create file and directory backups using the standard cp command and update the log file with the tee command at the same time. Here’s the command syntax for this operation.

# cp file.txt file_backup.txt | tee backup_log.txt

This command copies file.txt to file_backup.txt, and adds a copy of the contents to the backup_log.txt for record-keeping. Next, we used the cat command to check the contents of the file_backup.txt to verify the successful execution of the command.

Create Backup

Note: We recommend the secure copy (scp) command to transfer files on local and remote systems. 

Example #7: Monitor and Update Command Output

Consider the following command that monitors additions to a log file (using the tail -f command) and outputs the updates to the stdout (the terminal) and a log file (kern_backup.log). 

# tail -f kern.log | tee kern_backup.log

Monitor and Update Command Output

Example #8: Filtering and Saving Output

tee is an excellent solution for situations where you need to save a specific portion of a command’s output to a file. 

Consider the following command that uses tee to route specific portions of the output of the ps aux command. We used grep to filter the desired portions of the output that would be saved to different files (the lines containing root to root_processes.txt and the lines containing user to user_processes.txt:

ps aux | tee >(grep root > root_processes.txt) >(grep user > user_processes.txt)

Filtering and Saving Output

Example #9: Redirect the Standard Error (stderr)

In most cases, the standard error (stderr) is directed to stdout so that you can view the errors in the terminal. However, there are scenarios where you need to save the errors for later analysis or as input for other commands. 

Consider the following command that initiates a system-wide search (indicated by /) for file(s) named example.txt. The command redirects both the standard output (stdout) and standard error (stderr) to a file named search_results.txt. This file contains the results of the search (stdout) and any errors the process encountered (stderr). 

# find / -name "example.txt" 2>&1 | tee search_results.txt

Redirect the Standard Error

Fixing Frequently Occurring Common Issues

Even though using the tee command is usually simple, you may run into occasional glitches. We will now discuss several frequently occurring issues and their fixes.

Issue #1: Issues with Permission

Permission errors often occur when you use tee with commands that access specific resources such as files and processes. In this case, the command will fail with an error message about permission denied

Consider the following command that attempts to write to a file for which the user account doesn’t have the desired permission:

# ls -l | tee /root/file.txt

The output of the file would be similar to the following:
# tee: /root/file.txt: Permission denied

You can easily fix this issue by adding sudo to execute the tee command with increased privileges:

# ls -l | sudo tee /root/example.txt

# Output:

# total 0

# -rw-r--r-- 1 root root 0 Feb 2 12:34 file.txt

Issue #2: Overwriting Files

The default behavior of the tee command is to overwrite the contents of the target file. So, if you are not careful, you can easily wipe out previous data in logs and similar files. 

A simple fix is to use the -a (append) option to append to the file rather than overwrite it.

# echo 'Hello, World!' | tee hello.txt
# echo 'Hello, again!' | tee -a hello.txt
# cat hello.txt

Here, the first tee command writes Hello, World! to hello.txt. The second tee command appends Hello, again! to the file using the -a option. The cat command shows the file’s contents, indicating the presence of both lines of text.

Overwriting Files

Also Read: Mastering the Linux tee Command for Redirecting Output In 9 Examples

Conclusion

The tee Command is a powerful tool in the Linux command-line environment, allowing users to redirect output to multiple destinations simultaneously. The practical examples in this comprehensive guide give readers a deeper understanding of the tee‘s functionality and versatility. 

By exploring detailed explanations and practical examples, users have been equipped with the knowledge to leverage their day-to-day tasks effectively. Overall, the tee is a valuable tool for both beginners and experienced users alike, enhancing productivity and streamlining workflows through its ability to duplicate output streams effortlessly.

For mission-critical applications demanding top-tier performance, security, and reliability, consider partnering with RedSwitches. With a track record of excellence in the hosting industry, we offer a wide range of dedicated hosting solutions tailored to meet your specific needs. 

So, If you’re looking for a robust server for your Linux projects, we offer the best dedicated server pricing and deliver instant dedicated servers, usually on the same day the order gets approved. Whether you need a dedicated servers, a traffic-friendly 10Gbps dedicated server, or a powerful bare metal server, we are your trusted hosting partner.

FAQs

Q. What is the tee command in Linux?

The tee command in Linux is used to read from standard input and write to standard output and one or more files simultaneously. It allows you to capture the output of a command and view it on the terminal simultaneously.

Q. How do I use the tee command in Linux?

To use the tee command in Linux, you can simply pipe the command output to tee followed by the file name where you want to save the output. For example:
command | tee file.txt

Q. Can I redirect the output of a command using tee in Linux?

Yes, you can redirect the output of a command using the tee command in Linux. This can be done by piping the command output to a tee and specifying the file where you want to save the output. For example:
command | tee output.txt

Q. How can I append the output to a file using tee in Linux?

To append the output of a command to a file using the tee command in Linux, you can use the -a option. This will append the output to the specified file instead of overwriting it. For example:
command | tee -a output.txt

Q. Is it possible to redirect error output with a tee in Linux?

Yes, you can redirect error output along with the standard output using the tee command in Linux. This can be achieved by redirecting the standard error stream to a tee. For example:
command 2>&1 | tee output.txt

Q. How do I output multiple files simultaneously with tee in Linux?

Using the tee command in Linux, you can specify multiple file names after tee to output to multiple files simultaneously. For example:
command | tee file1.txt file2.txt

Q. How can command-line arguments be passed to tee in Linux?

Command-line arguments can be passed to the tee in Linux by specifying them after the tee command, such as echo “Hello” | tee -a output.txt.

Q. Can tee be used to write to a root-owned file in Linux?

Using tee to write to a root-owned file in Linux may require elevated privileges or sudo to ensure proper permissions.

Q. Can the tee command preserve the original contents of the target file?

We recommend using the append option (-a )to retain the original contents of the file and add new content at the end. 

Q. Can tee be used for complex tasks in Linux?

The tee command can be integrated into more complex tasks or scripts to manage and manipulate data streams effectively.

Try this guide with our instant dedicated server for as low as 40 Euros