Pipelines and redirection: Which UNIX command duplicates standard output to the terminal while simultaneously saving it to a file?

Difficulty: Easy

Correct Answer: tee

Explanation:


Introduction / Context:
Sometimes you want to capture output for logs while still seeing it live. The tee utility solves this by splitting a stream: it writes to a file and passes the same data along to standard output. This is invaluable in pipelines and troubleshooting sessions.



Given Data / Assumptions:

  • The goal is to save command output to a file without losing on-screen visibility.
  • You are using a POSIX shell and standard utilities.
  • Overwriting vs appending may matter depending on workflow.


Concept / Approach:
Use a pipeline: command | tee file. tee writes its standard input to file and also to standard output, enabling further piping or terminal display. The -a option appends instead of overwriting.



Step-by-Step Solution:

Example: who | tee user.lstAppend mode: make build 2>&1 | tee -a build.logChain further: dmesg | tee dmesg.txt | grep errorVerify: view the file and confirm output also appeared on screen.


Verification / Alternative check:
Compare with redirection > (overwrites) or >> (appends) which do not mirror output to the screen. tee is unique in duplicating the stream.



Why Other Options Are Wrong:
grep: filters lines by pattern only. cat: displays files; does not duplicate streams to a file and stdout simultaneously without redirection tricks. more: pager for reading, not for splitting output. None of the above: incorrect because tee is correct.



Common Pitfalls:
Forgetting -a when you need to append; accidentally truncating logs. Not capturing stderr unless redirected (use 2>&1 to combine streams).



Final Answer:
tee

Discussion & Comments

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