In Unix/Linux pipelines, which command reads from standard input, writes the same data to standard output, and simultaneously copies it into a file?

Difficulty: Easy

Correct Answer: tee

Explanation:


Introduction / Context:
Sometimes you need to both see command output on the screen and save it to a file for later analysis. Instead of running the pipeline twice or redirecting and then catting, Unix provides a filter that duplicates the stream transparently to multiple outputs.


Given Data / Assumptions:

  • You have a pipeline producing useful output on stdout.
  • You want to preserve that output in a file without losing the live display.
  • Standard POSIX tools are available.


Concept / Approach:
The 'tee' command splits its standard input and writes it to both standard output and one or more files. Common options include '-a' to append instead of overwrite. 'tee' is ideal for logging build processes, capturing diagnostic streams, or auditing scripts while maintaining interactive visibility.


Step-by-Step Solution:

Basic usage: cmd | tee output.logAppend to a file: cmd | tee -a output.logWrite to multiple files: cmd | tee out1.log out2.logCombine with sudo where root write is needed: cmd | sudo tee /root/out.log


Verification / Alternative check:
Run a pipeline such as 'dmesg | tee dmesg.txt' and confirm that output appears on screen and that the file contains identical content afterwards.


Why Other Options Are Wrong:

  • tr: Translates or deletes characters; does not duplicate streams to files.
  • sort: Orders lines; not a duplicator.
  • grep: Filters lines by pattern; does not copy to files and stdout simultaneously.
  • None of the above: Incorrect because 'tee' is exactly designed for this.


Common Pitfalls:
Overwriting a file unintentionally without '-a', forgetting to redirect stderr separately if needed (use '2>&1' before tee), or misplacing 'sudo' which can change which side of the pipe has elevated permissions.


Final Answer:
tee

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion