Terminal · foundation
Redirection
Redirection is shell syntax that opens, closes, or duplicates file descriptors for a command before that command begins executing.
Why it matters
Redirection controls where commands read and write, but its ordering and overwrite behavior can silently lose data or combine the wrong streams.
Mental model
How to reason about redirection
Read redirections from left to right as wiring instructions: each step changes one descriptor using the connections that exist at that moment.
Analogy
It resembles reconnecting labeled hoses before turning on a machine; the order matters when one hose is attached to wherever another hose currently leads.
Examples
See the boundary, not just the happy path
Worked example · Replace versus append
printf '%s\n' first > run.log; printf '%s\n' second >> run.log> opens run.log for replacement, while >> opens it for append, leaving two lines after both commands.
Worked example · Combine both output streams
build > build.log 2>&1The shell first points stdout at build.log, then duplicates that current stdout connection onto stderr, so both streams share the file.
Useful contrast · Order changes the wiring
build 2>&1 > build.logstderr first copies the shell's original stdout, then stdout moves to the file; diagnostics therefore do not follow stdout into build.log.
Common mistakes
Misconceptions to remove early
Overwriting before the command can read
The shell opens output redirections before launching the command, so sort data.txt > data.txt can truncate the input before sort reads it.
Treating 2>&1 as a permanent link
Descriptor duplication copies the current connection; later redirection of descriptor 1 does not automatically update descriptor 2.
Quick check
Can you predict the result?
1. Which operator appends standard output instead of replacing the destination file?
- • >>
- • >
- • <
2. Why do build >log 2>&1 and build 2>&1 >log behave differently?
Keep building