In this lesson, you will learn how the shell manipulates the kernel’s internal file descriptor table to reroute data between processes and files.
The File Descriptor Table
When you run a command in Linux, the kernel assigns it a table of "File Descriptors" (FDs). By default, every process starts with three:
- 0 (Standard Input/stdin): Where the process listens for data.
- 1 (Standard Output/stdout): Where the process writes its results.
- 2 (Standard Error/stderr): Where the process sends diagnostic messages.
Think of these as labeled slots in a mailbox. Redirection isn't magic; it is simply the act of the shell asking the kernel to swap out what is behind those slots before the command starts executing.
How Redirection Happens
When you type ls > file.txt, the shell doesn't just "send output to a file." Instead, it performs a low-level operation:
- Duplicate: It takes the file descriptor representing
file.txtand moves it into slot1. - Overwrite: The original occupant of slot
1(usually the terminal screen) is closed or pushed aside. - Execute: The
lscommand runs, completely unaware that slot1is no longer the screen. It simply writes to "1," and the kernel delivers that data to the file instead.
You can observe this "swapping" mechanism with the >& syntax. Consider this command:
ls 2>&1
Here, the shell instructs the kernel to take whatever is currently in slot 1 (stdout) and duplicate it into slot 2 (stderr). Now, both slots point to the same destination. If you had previously redirected stdout to a file, stderr will now follow it into that exact same file because it has been pointed to the same memory address in the file descriptor table.
Understanding this allows you to chain complex streams, such as sending both regular output and error logs into a single file while keeping the terminal clean for the user.
Key Takeaway: Redirection is the act of reassigning the destination of a file descriptor slot (0, 1, or 2) in the process's internal table before the command begins execution.