Course contentsShow
← Linux
Lesson 294 of 1,8193. The Filesystem Hierarchy and POSIX StandardsFree lesson

Standard Streams and Redirection

Manipulate process input, output, and error streams using standard file descriptor behaviors.

Mastering Standard Streams and Redirection

In this lesson, you will learn how to control where a program sends its output and where it pulls its input by manipulating standard streams.

The Three Standard Streams

Every process in Linux starts with three open communication channels, known as file descriptors:

  1. Standard Input (stdin, file descriptor 0): Where the program reads data (usually your keyboard).
  2. Standard Output (stdout, file descriptor 1): Where the program sends its normal results (usually your terminal screen).
  3. Standard Error (stderr, file descriptor 2): Where the program sends error messages or diagnostic info, keeping them separate from regular output.

Redirecting Streams

Redirection allows you to route these streams to files or other processes instead of the default terminal display. We use specific operators to handle them:

  • > (Stdout Redirection): This sends the standard output of a command into a file, overwriting the file if it exists.

    ls /home > my_files.txt
    

    Here, the list of files is saved into my_files.txt instead of appearing on your screen.

  • 2> (Stderr Redirection): This sends error messages to a specific location. This is incredibly useful for filtering out noise.

    find / -name "*.conf" 2> errors.log
    

    If the command encounters "Permission denied" errors, they are safely captured in errors.log, leaving your screen clean for the actual results.

  • < (Stdin Redirection): This tells a command to read input from a file instead of waiting for your keyboard.

    sort < input_list.txt
    

Combining Streams

Sometimes you want both output and error messages in the same place. You can redirect stderr (2) to the same location as stdout (&1) using the 2>&1 syntax:

command > output.log 2>&1

By mastering these redirections, you gain total control over the flow of data in your Linux environment, allowing you to automate tasks and maintain cleaner logs without needing complex code.

Key Takeaway: Standard streams provide a universal interface for processes to communicate, and redirection operators allow you to route that data to files or other streams to build powerful, automated workflows.