The Purpose of the tee Command

The tee command in Bash is a utility that reads from standard input and writes to standard output and one or more files simultaneously. It is particularly useful for capturing the output of a command while still allowing that output to be displayed on the terminal. This makes tee an essential tool for logging and debugging in shell scripts and command-line operations.

Basic Syntax of the tee Command

The basic syntax for the tee command is as follows:

command | tee [options] file_name

In this syntax:

  • command is the command whose output you want to capture.
  • file_name is the name of the file where the output will be saved.
  • [options] are optional flags that modify the behavior of the command.

Example of Using tee

1. Basic Usage

Here’s a simple example of using the tee command to capture the output of a command:

echo "Hello, World!" | tee output.txt

In this example:

  • The command echo "Hello, World!" sends the string Hello, World! to the tee command.
  • The output is displayed on the terminal and simultaneously written to the file output.txt.

2. Appending to a File

By default, tee overwrites the specified file. To append the output to an existing file instead, you can use the -a option:

echo "This is a new line." | tee -a output.txt

In this example:

  • The command appends the string This is a new line. to the end of output.txt while also displaying it on the terminal.

3. Capturing Output from a Command

You can use tee to capture the output of more complex commands. For example:

ls -l | tee directory_listing.txt

In this example:

  • The command ls -l lists the files in the current directory in long format.
  • The output is displayed on the terminal and saved to directory_listing.txt.

4. Using tee with Multiple Files

You can also use tee to write output to multiple files at once:

echo "Logging output" | tee file1.txt file2.txt

In this example:

  • The command writes the string Logging output to both file1.txt and file2.txt, while also displaying it on the terminal.

Conclusion

The tee command is a versatile tool in Bash that allows you to capture and log command output while still displaying it on the terminal. Its ability to write to multiple files and append to existing files makes it invaluable for logging, debugging, and monitoring processes in shell scripts and command-line operations. By mastering the use of the tee command, you can enhance your command-line productivity and maintain better control over your output data.