Skip to main content
We’ll cover how to redirect input and output in Linux — a foundational skill for shell scripting, automation, and command-line workflows.
A dark-themed presentation slide with the title "Redirecting Input and Output" on the left and a large empty rounded rectangle area on the right. The KodeKloud logo appears in the top-right corner.
Why this matters: most Unix utilities read from stdin (standard input) and write to stdout (standard output). Redirecting these streams — and stderr (standard error) — lets you capture program output, suppress errors, chain commands, and feed files into programs that expect interactive input.

Basic example (sort)

Many commands accept a filename argument, but they also work with stdin/stdout. For example, sort reads text and prints sorted lines:

Redirecting stdout: overwrite vs append

  • overwrites (creates the file if it doesn’t exist).
  • appends to the file.
Example — overwrite (only the last run remains):
Example — append (each timestamp preserved):
Quick comparison:

File descriptors and common redirections

Programs use three standard streams: Common redirection operators:
File descriptors: 0 = stdin, 1 = stdout, 2 = stderr. Use 2> to redirect error messages separately from normal output.

Discard unwanted output: /dev/null

Send output you don’t want to see to /dev/null — a special sink that discards everything. Example: hide permission-denied messages from a recursive grep:

Redirect stdout and stderr separately

Capture normal output and errors in different files:

Redirect both stdout and stderr to the same file

To collect both streams into one file, redirect stdout first, then redirect stderr to stdout with 2>&1. The order matters:
Why order matters:
  • 1>all_output.txt sets stdout to the file.
  • 2>&1 then points stderr to wherever stdout is currently going (the file). If you reverse the order (2>&1 1>file), stderr is redirected to the original stdout (the terminal) before stdout is redirected, so errors still appear on-screen.

Input redirection (<) and feeding commands

Some programs read from stdin instead of accepting a filename. Use < to provide a file as stdin:

Here-documents and here-strings

Use here-documents (heredocs) for multi-line inline input. Terminate with the chosen delimiter (EOF is common):
Here-strings pass a single string to stdin using <<<:

Piping: chain small tools

Pipes (|) send the stdout of one command into the stdin of the next. This enables powerful one-line workflows: Example — remove commented lines, sort, and column-format the file:
Pipes are essential for combining simple Unix tools into effective data-processing chains — searching, sorting, formatting, counting, and more.

Quick reference: common patterns

Further reading and references

That’s all for this lesson.

Watch Video

Practice Lab