ch03/l01

stdin, stdout, stderr

Know which stream carries data and which carries diagnostics.

2> 20 min read, 20 min lab foundation

Unix commands commonly read stdin, write normal output to stdout, and write diagnostics to stderr. Redirection changes where those streams go. Mixing them carelessly can hide failures or pollute data files.

In the field

A nightly report should capture results but keep errors visible for investigation.

Worked command

$ grep -rn "ERROR" ./logs > errors.txt$ grep -rn "ERROR" ./missing > errors.txt 2> grep.err$ cat grep.err
Anti-pattern

Do not redirect all output away just to make a command quiet.

Safer pattern

Decide whether you are collecting data, errors, or both before redirecting.

Knowledge check

You run `grep -rn ERROR ./missing > errors.txt` and the path doesn't exist. Where does the error message go and why?

  • A To errors.txt, because > captures everything the command emits
  • B To the screen, because > only redirects stdout and errors go to stderr
  • C Nowhere; the redirect suppresses it and errors.txt stays empty
  • D To the screen, because grep always prints errors before opening the file
Show the answer

Correct: B. To the screen, because > only redirects stdout and errors go to stderr

Why

`>` redirects only stdout (fd1); diagnostics go to stderr (fd2), which is untouched and still on the terminal. The first option is the common trap — `>` does not capture stderr, so to send it to a file you need a separate `2>`.

Practice checklist

  1. Run a successful grep redirected to a file.
  2. Run a failing grep with stderr redirected separately.
  3. Inspect both files.

Deliverable evidence

  • Two redirected commands and a note naming stdout and stderr.
Teaching diagramch03 · mental model
three streams, redirected separately stdin fd 0 command grep / sort stdout fd 1 > file stderr fd 2 2> file stdout pipes to next stage; stderr stays on screen > redirects fd1 only — fd2 needs its own 2>

shows: A command reads stdin (fd0) and writes two independent outputs — stdout (fd1) and stderr (fd2) — each redirectable on its own, so `>` captures data while `2>` captures diagnostics.

does not prove: It shows the wiring of the three streams, not that any given command actually sends errors to stderr — a few tools misroute diagnostics to stdout, so you still confirm by inspecting both targets.

Memorize this

Commit these to memory, then drill them until recall is automatic.

>>>2>stdoutstderr
Recall practice · Meaning -> command

cue Send a command's error messages to a file while leaving its normal output alone

show recall target

2> errors.txt