Skip to main content
In this lesson, you’ll master how to redirect input and output in Linux, making your command-line workflows more powerful and flexible.

Table of Contents

  1. Standard Streams Overview
  2. Redirecting Output
  3. Appending Output
  4. Discarding Output
  5. Merging and Redirecting Both Streams
  6. Redirecting Input
  7. Here Documents and Here Strings
  8. Pipes and Pipelines
  9. Quick Reference
  10. Links and References

Standard Streams Overview

Linux programs communicate using three standard streams:
The image is a diagram illustrating the flow of standard input, output, and error in a command-line environment, showing how data from "file.txt" is processed by the "sort" command, with output directed to a terminal and errors to "errors.txt".
By default, both stdout and stderr appear on your terminal. You can redirect them separately:

Redirecting Output (>)

To save a command’s output to a file (creating or overwriting it), use the > operator.
  1. Create a file with unsorted numbers:
  2. Sort the file and write the result to sortedfile.txt:
Using > always overwrites the target file. You will lose previous contents!

Appending Output (>>)

To add output to the end of an existing file without erasing its contents, use >>:

Discarding Output (/dev/null)

Send unwanted output or errors to /dev/null, the “black hole”:
This filters matching lines while discarding all error messages.

Merging and Redirecting Both Streams

  • Redirect stdout and stderr to separate files:
  • Append both streams:
  • Merge stderr into stdout and write to one file:
Order matters: > all_output.txt 2>&1 merges error output into the same file, while reversing redirects leaves errors on the console.

Redirecting Input (<)

Some commands read from stdin instead of a file argument. Redirect a file into stdin like this:
The contents of email_content.txt feed directly into sendemail.

Here Documents and Here Strings

Here Documents (<<)

Embed a block of text as input:
EOF (or any marker you choose) encloses the input region.

Here Strings (<<<)

For single-line input, here strings are concise:

Pipes and Pipelines (|)

Pipelines let you chain commands by feeding one’s stdout into the next’s stdin. Example: filter, sort, and align columns from /etc/login.defs:
Steps:
  1. grep -v '^#' removes comments
  2. sort orders lines
  3. column -t aligns columns into a neat table
Example output:

Quick Reference

Watch Video