Guide to redirecting stdin, stdout, and stderr in Unix shells, covering redirection operators, pipes, here-documents, suppression, and common patterns for command-line workflows.
We’ll cover how to redirect input and output in Linux — a foundational skill for shell scripting, automation, and command-line workflows.
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.
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:
Copy
# Without suppression: stderr clutter$ grep -r '^The' /etc/grep: /etc/cups/ssl: Permission denied...# Suppress stderr by redirecting it to /dev/null$ grep -r '^The' /etc/ 2>/dev/null/etc/brltty/Input/tn/all.txt:The two keys at the left rear (2 columns, 1 row):...
To collect both streams into one file, redirect stdout first, then redirect stderr to stdout with 2>&1. The order matters:
Copy
# Correct: both streams go into all_output.txt$ grep -r '^The' /etc/ > all_output.txt 2>&1# Equivalent with explicit descriptor$ grep -r '^The' /etc/ 1>all_output.txt 2>&1
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.
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:
Copy
# Show non-comment lines$ grep -v '^#' /etc/login.defs# Pipe into sort$ grep -v '^#' /etc/login.defs | sort# Pipe into column for neat alignment$ grep -v '^#' /etc/login.defs | sort | column -tCREATE_HOME yesENCRYPT_METHOD SHA512GID_MAX 60000...
Pipes are essential for combining simple Unix tools into effective data-processing chains — searching, sorting, formatting, counting, and more.