Redirection & Pipes

Streams & Redirection

Every process on Linux is born with three open communication channels already connected, whether it uses them or not - these are the standard streams, and understanding them is the key to everything that follows in this module.

StreamFDDefault
stdin0keyboard
stdout1terminal
stderr2terminal

stdin is where a program reads input from (normally your keyboard). stdout is where its normal output goes (normally your screen). stderr is a separate channel for error messages - kept apart from stdout specifically so that a program's real output and its error chatter can be redirected independently, e.g. saving results to a file while still seeing errors on screen. Each stream has a numeric file descriptor (0, 1, 2) that redirection operators reference directly.

Analogy: Think of a process like a customer service desk with three separate slots: one where requests come in (stdin), one where completed paperwork comes out (stdout), and a separate "problems" tray (stderr) that's kept apart precisely so a supervisor reviewing completed paperwork isn't wading through complaint slips mixed in with it.
OperatorEffect
>Redirect stdout (overwrite)
>>Redirect stdout (append)
2>Redirect stderr
&>Redirect stdout and stderr
2>&1Send stderr to wherever stdout goes
<Redirect stdin from a file
`\`Pipe stdout into another command's stdin
teeWrite to a file and pass through

2>&1 is the one that confuses people the first time: it doesn't mean "redirect stderr to a file named 1" - the & before the 1 specifically means "treat this as a file descriptor reference, not a filename," so it reads as "send stderr to wherever file descriptor 1 (stdout) is currently pointing."

$ command > out.log 2>&1        # both streams to one file
$ ls /nope 2> /dev/null         # discard errors
$ dmesg | grep -i error | tee errors.txt | wc -l

/dev/null is a special device file that silently discards anything written to it - the standard way to say "I don't want to see this output at all." The tee example shows the pipe chaining you'll use constantly: dmesg's output flows into grep to filter for errors, tee saves a copy to errors.txt while also passing everything through unchanged, and wc -l counts how many lines made it through.

Warning: Order matters, and it's a genuinely common trap: command > file 2>&1 correctly sends both streams to file, because by the time 2>&1 runs, stdout has already been pointed at file. But command 2>&1 > file does something different - at that point stdout is still pointing at the terminal, so 2>&1 sends stderr to the terminal too, and only then does > file redirect stdout (alone) to the file. The two error streams end up in different places depending purely on left-to-right order.