Pipelines and tee: connect Linux commands
Quick answer
A pipeline connects one command’s standard output to the next command’s standard input. Build a report in steps instead of opening temporary files for every intermediate result. tee lets you keep a copy of the passing data while continuing to display or process it.
Prepare the practice environment
Use the chapter fixture described in lab-fixtures/text-streams/README.md. Run setup as a normal user in a disposable Linux environment, enter the printed directory and check pwd. Every example assumes a fresh fixture. Commands omit the terminal prompt; outputs below are not commands.
How it works
In A | B, A and B normally run concurrently; the pipe carries bytes, not a shared shell variable. Only stdout is connected by an ordinary |, while stderr keeps its previous destination unless redirected. tee FILE writes its input to FILE and stdout; tee -a appends. A pipeline may fail even when the last command succeeds: Bash normally reports the status of the last command, but set -o pipefail makes it report the rightmost nonzero status, or zero if all succeed. The subshell parentheses in the example limit that setting to the example. Further shell options belong to the Bash track.
A pipe connects the producer to the consumer, while tee copies the bytes it receives to a file and forwards them. A file created by tee may be empty or incomplete; its existence does not prove that every upstream operation succeeded. In a script that requires all stages to succeed, inspect the pipeline status under the intended Bash settings.
Try the examples
head sends two lines into the pipe; wc reads them as stdin.
Expected stdout:
2head -n 2 events.txt | tee preview.txtcat preview.txtThe first pair is tee output; the second is the verification read of the saved copy.
Expected stdout:
startcheckstartcheck( set +o pipefail; false | true; printf '%s\n' "$?" )( set -o pipefail; false | true; printf '%s\n' "$?" )The intentionally failing first command is hidden by the last status in the first case but visible with pipefail.
Expected stdout:
01Common mistakes
Tee overwrites its output file by default. Never use a pipeline to read and overwrite the same file. Do not infer success from the existence of an output file; check status and validate the content.
Practice
Save the last two lines of events.txt using tail and tee, then count the saved lines. Predict what happens if tee -a is run twice.
Related references
Study: tee, wc. These are reference names, not deployed links.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Pipelines and tee — Knowledge Check
Apply the lesson concepts to the controlled text fixture.
What does an ordinary | connect?
Which command copies input to a file and stdout?
Which tee option appends?
What does pipefail change?