Posted on
Advanced

Understanding and Using `tee` for Capturing Output

Author
  • User
    Linux Bash
    Posts by this author
    Posts by this author

The tee command in Unix-like operating systems is a powerful utility for capturing and duplicating command output. It allows you to both display the output of a command on the terminal and simultaneously write it to a file. Here's a detailed guide to understanding and using tee.


Basic Syntax

command | tee [options] [file...]
  • command: The command whose output you want to capture.
  • |: A pipe that passes the output of command to tee.
  • tee: The command that reads from standard input and writes to standard output and file(s).
  • file...: One or more files where the output will be saved.

How tee Works

  1. Standard Output Display: tee sends the output to the terminal (standard output).
  2. File Saving: Simultaneously, it writes the same output to one or more specified files.

Common Use Cases

1. Log Output While Viewing

To log output to a file while still seeing it in real time on the terminal:

ls -l | tee output.txt

2. Append to a File

By default, tee overwrites the file. Use the -a option to append instead:

ls -l | tee -a output.txt

3. Capture and Process Output

You can use tee in pipelines to split the output for multiple processing streams:

cat file.txt | tee intermediate.txt | grep "pattern"

Here: - The content of file.txt is saved in intermediate.txt. - The grep command processes the same output.

4. Save Multiple Outputs

Save output to multiple files simultaneously:

ls -l | tee file1.txt file2.txt

5. Debugging Scripts

Log the output of a script while running it interactively:

./script.sh | tee debug.log

Common Options

  • -a: Append the output to the file(s) instead of overwriting.
  • -i: Ignore interrupt signals, ensuring tee continues writing even if interrupted.

Practical Examples

Redirect Standard Error (stderr)

To capture both standard output (stdout) and standard error (stderr):

command 2>&1 | tee output.txt

Save Output for Multiple Commands

Using tee in a multi-stage pipeline:

command | tee temp.txt | another_command

Interactive Use with Sudo

When saving files requiring elevated permissions:

command | sudo tee /path/to/protected_file

Tips

  • Use tee for monitoring logs in real-time during processes like backups or deployments.
  • Be cautious when overwriting files, as tee overwrites without confirmation unless -a is used.

The tee command enhances command-line workflows by providing a simple way to capture, inspect, and process output without disrupting its flow.