In this lesson, you will learn how to send a single command's output to multiple destinations simultaneously, such as displaying it on your screen while also saving it to a log file.
Why Multiplex Streams?
Usually, when you run a command, you either see the output in your terminal (stdout) or you redirect it to a file using >. But what if you need both? You want to monitor the progress of a long-running script in real-time, but you also need a permanent record of the execution for later auditing.
In Linux, we solve this with the tee command. Think of tee like a plumbing T-junction: the command’s output flows into the tool, which then splits it, sending one copy to the console and another copy to a file (or multiple files).
Practical Usage
Imagine you are running a script that takes a long time and you want to ensure you capture every bit of information. Instead of just running ./script.sh > log.txt, which hides the output from your view, you use a pipe:
./my_script.sh | tee run_log.txt
In this example, my_script.sh writes its output to stdout, the pipe | catches it, and tee pushes that stream into two directions: your terminal screen and run_log.txt.
Handling Errors
Remember that tee only handles the standard output stream (stdout). If your script prints error messages (stderr), they will still print to the screen and bypass the log file. To capture both standard output and errors in your multiplexed stream, you must redirect the error stream into the standard output stream first:
./my_script.sh 2>&1 | tee run_log.txt
By combining 2>&1 (which merges errors into the standard output stream) with the pipe into tee, you ensure that every single message produced by your script is both visible on your display and safely stored in your file. This approach is standard practice for creating reliable, traceable logs in automated workflows.
Key Takeaway: The tee command acts as a multiplexer that allows you to monitor command output in real-time while simultaneously archiving it to a file.