Course contentsShow
← Linux
Lesson 43 of 1,8191. Shell Architecture and Process EnvironmentFree lesson

Redirecting File Descriptors

Manipulate standard input, output, and error streams using advanced file descriptor redirection.

In this lesson, you will learn how to precisely control where your commands send their data by manipulating the three primary communication channels, known as file descriptors.

The Three Standard Streams

Every process you run in Linux starts with three default channels open:

  1. File Descriptor 0 (Standard Input / stdin): Where the process reads information.
  2. File Descriptor 1 (Standard Output / stdout): Where the process writes its successful results.
  3. File Descriptor 2 (Standard Error / stderr): Where the process sends warning or error messages.

Usually, all three are connected to your terminal window. Redirecting allows you to detach these streams from the screen and point them toward files or other processes.

Practical Redirection

You are likely familiar with > to send output to a file, but you can target specific descriptors by prefixing the redirection operator with the descriptor number. For instance, if you want to capture error messages separately from successful output, you can do this:

ls /nonexistent_folder > results.txt 2> errors.txt

In this example, the successful output (descriptor 1) goes to results.txt, while any error generated (descriptor 2) is sent to errors.txt.

You can also merge two streams together. If you want to log everything to the same file, you can "redirect" descriptor 2 to point to where descriptor 1 is currently going:

ls /nonexistent_folder > log.txt 2>&1

Here, the 2>&1 syntax tells the shell: "Take the error stream and send it to the same destination as the output stream." This is a powerful technique for logging complete process history, including what went wrong during execution. By mastering these numeric handles, you stop being a passive user and start actively managing how your processes handle their data flow.

Key Takeaway: File descriptors 0, 1, and 2 act as the input/output ports of a process, and you can redirect them independently or merge them using their numeric identifiers to control exactly where data lands.