Course contentsShow
← Linux
Lesson 232 of 1,8192. Deep Dive into Bash ScriptingFree lesson

Redirection Internals

Understand the low-level manipulation of file descriptor tables.

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:

  1. Duplicate: It takes the file descriptor representing file.txt and moves it into slot 1.
  2. Overwrite: The original occupant of slot 1 (usually the terminal screen) is closed or pushed aside.
  3. Execute: The ls command runs, completely unaware that slot 1 is 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.