How to Use tee Command in Linux

The tee command in Linux reads input from stdin, writes it to stdout, and simultaneously saves it to one or more files. This is particularly useful when you want to view output in the terminal while also saving it for later use.

Alby Andersen

The tee command in Linux reads from standard input and writes to both standard output and one or more files simultaneously. It acts like a “T-splitter” for data streams, allowing you to view output in real-time while saving it to a file.

This is especially useful for debugging, logging, or monitoring command output without disrupting pipelines. Below are practical examples to master tee:

Save Output to a File While Viewing It

ls -l | tee directory_list.txt
  • Lists directory contents and saves the output to directory_list.txt.

Append to a File Instead of Overwriting

echo "New log entry" | tee -a app.log
  • -a appends the text to app.log instead of overwriting it.

Write to Multiple Files

dmesg | tee system.log boot.log
  • Saves the kernel ring buffer output to both system.log and boot.log.

Use with sudo to Write to Protected Files

echo "127.0.0.1 test.local" | sudo tee -a /etc/hosts
  • Uses sudo to append a line to the protected /etc/hosts file.

Capture Intermediate Pipeline Output

grep "ERROR" app.log | tee errors.txt | wc -l
  • Saves error lines to errors.txt while counting them with wc -l.

Combine with grep for Filtered Logging

journalctl -u nginx | tee nginx_logs.txt | grep "404"
  • Saves full Nginx logs to nginx_logs.txt while filtering for “404” errors.

Ignore Interrupt Signals (Continue Writing)

ping google.com | tee -i ping_results.txt
  • -i ensures tee continues writing even if interrupted (e.g., Ctrl+C).

Split Output into Files and Terminal

ls /usr/bin | tee all_programs.txt featured_programs.txt
  • Lists programs in /usr/bin and saves the output to two files.

Use with Process Substitution

ls -l | tee >(gzip > dirlist.gz) >(awk '{print $9}' > filenames.txt)
  • Saves raw output to dirlist.gz (compressed) and filenames to filenames.txt.

Suppress Terminal Output

curl -s http://example.com | tee response.html > /dev/null
  • Downloads a webpage silently and saves it to response.html.

Use with df to Monitor Disk Space

df -h | tee disk_usage.log

Displays disk usage statistics and logs them to disk_usage.log.


Key Notes:

  • Overwriting: By default, tee overwrites files. Use -a to append.
  • Permissions: Use sudo tee when writing to system-protected files.
  • Pipelines: Place tee anywhere in a pipeline to capture intermediate data.

Featured Image: Wikimedia, CC BY-SA 4.0

Share This Article