Lab 17: I/O Redirection and Pipes

Objective

Master standard streams (stdin, stdout, stderr), redirection operators (>, >>, 2>, &>), and the pipe | for chaining commands. Pipes are what make Linux so powerful — dozens of simple tools combined into complex workflows.

Time: 30 minutes | Level: Foundations | Docker: docker run -it --rm ubuntu:22.04 bash


Step 1: The Three Standard Streams

Every Linux process has three streams:

  • stdin (0) — input (keyboard by default)

  • stdout (1) — output (terminal by default)

  • stderr (2) — errors (terminal by default)

# stdout goes to terminal
echo 'Hello World'

📸 Verified Output:

Hello World
# stderr goes to terminal too (same place, different stream)
cat /nonexistent 2>&1

📸 Verified Output:


Step 2: Redirecting stdout

📸 Verified Output:

📸 Verified Output:

💡 > is destructive — it truncates the file first. >> is safe — it always appends. When in doubt, use >>. Many production incidents started with > logfile instead of >> logfile.


Step 3: Redirecting stderr

📸 Verified Output:

📸 Verified Output:

💡 /dev/null is the black hole of Linux — anything written to it disappears. Perfect for suppressing noise: find / -name passwd 2>/dev/null hides all the "Permission denied" errors.


Step 4: Combining stdout and stderr

📸 Verified Output:

📸 Verified Output:


Step 5: Pipes — Connecting Commands

📸 Verified Output:

📸 Verified Output:

📸 Verified Output:

💡 Each pipe creates a mini-pipeline in memory — data flows from left to right without writing temp files. The shell connects stdout of one process directly to stdin of the next.


Step 6: Useful Pipeline Tools

📸 Verified Output:

📸 Verified Output:

📸 Verified Output:

📸 Verified Output:


Step 7: tee — Split the Pipeline

📸 Verified Output:

💡 tee is invaluable in long pipelines where you want to save intermediate results while still processing further. command | tee output.txt | grep ERROR saves everything but only shows errors.


Step 8: Capstone — Log Analysis Pipeline

📸 Verified Output:


Summary

Operator
Meaning

>

Redirect stdout (overwrite)

>>

Redirect stdout (append)

2>

Redirect stderr

2>/dev/null

Discard stderr

&>

Redirect stdout + stderr

2>&1

Redirect stderr to stdout

|

Pipe stdout to next command's stdin

tee file

Write to file AND pass through

Last updated