Every process has stdin (0), stdout (1), and stderr (2). Redirection connects them to files or pipes.
Stdout and stderr
echo "ok" > out.txt
echo "error" >&2
echo "both" >> out.txt
cat out.txt> truncates; >> appends. 2> targets stderr.
Combine streams
command 2>&1 | tee log.txt2>&1 merges stderr into stdout before piping—order matters: 2>&1 after redirecting stdout.
Here string
grep "error" <<< "line1
error: disk
line3"A here-string feeds a string as stdin—useful for tiny tests without temp files.
Important interview questions and answers
- Q: > vs >>?
A: > truncates the file; >> appends to the end. - Q: What is file descriptor 2?
A: Standard error—use 2> to capture or discard errors separately.
Self-check
- Which operator appends stdout to a file?
- How do you send stderr to the same place as stdout before a pipe?
Pitfall: Order matters: 2>&1 after redirecting stdout when merging streams.
Interview prep
- > vs >>?
> truncates; >> appends.
- 2>&1 meaning?
Redirect stderr to wherever stdout currently goes.