Concept

Redirection

Definition

Redirection is the set of shell operators that connect a command's standard streams — standard input (file descriptor 0), standard output (file descriptor 1), and standard error (file descriptor 2) — to files, other processes, or other file descriptors. The basic operators are > (write stdout to a file, truncating), >> (append stdout to a file), < (read stdin from a file), | (pipe stdout of one command to stdin of the next), and 2>&1 (redirect stderr to wherever stdout currently goes). Together they let small single-purpose programs be composed into elaborate data pipelines without any program needing to know about any other.

Redirection is the operational expression of the Unix philosophy: each program reads from one stream, writes to another, and the shell is responsible for wiring the streams together. The full Unix toolkit — grep, sort, uniq, awk, sed, cut, tr, xargs — is designed around this contract.

Why it matters

How it works

Each redirection is implemented as a dup2() system call that the shell performs after fork() and before exec(). When you write cmd > out.txt, the shell forks a child, opens out.txt for writing, and then uses dup2() to make file descriptor 1 (stdout) point to the same file as the newly-opened descriptor. By the time exec() runs cmd, its file descriptor 1 already refers to the file — cmd itself has no idea its output is being captured. The same mechanism with file descriptor 0 connects stdin; with file descriptor 2 it connects stderr.

A pipe is the same idea between two processes. The shell calls pipe() to create a kernel-managed buffer with a read end and a write end, forks two children, connects the first child's stdout to the write end and the second's stdin to the read end, and execs the two commands. Data the first writes is buffered by the kernel and read by the second. The 2>&1 syntax means "make file descriptor 2 a duplicate of whatever 1 currently points to" — which is why the order around a > redirection matters: > file 2>&1 first sends stdout to the file, then sends stderr to where stdout now goes (the file); 2>&1 > file first sends stderr to the terminal (where stdout currently goes), then sends stdout to the file.

Where it goes next

Continue exploring

Tags