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.
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
Do not redirect all output away just to make a command quiet.
Decide whether you are collecting data, errors, or both before redirecting.
You run `grep -rn ERROR ./missing > errors.txt` and the path doesn't exist. Where does the error message go and why?
Show the answer
Correct: B. To the screen, because > only redirects stdout and errors go to stderr
`>` 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
- Run a successful grep redirected to a file.
- Run a failing grep with stderr redirected separately.
- Inspect both files.
Deliverable evidence
- Two redirected commands and a note naming stdout and stderr.
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.
Commit these to memory, then drill them until recall is automatic.
cue Send a command's error messages to a file while leaving its normal output alone
show recall target
2> errors.txt