
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.
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:- 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):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:Quick reference: common patterns
Further reading and references
- Bash manual — Redirections: https://www.gnu.org/software/bash/manual/html_node/Redirections.html
- Unix I/O and file descriptors overview: https://en.wikipedia.org/wiki/Standard_streams
- Advanced shell scripting techniques (pipes, heredocs): https://tldp.org/LDP/abs/html/