Standard streams and descriptors
A command can receive input, send normal results, and report diagnostics through separate channels. Bash inherits standard input (stdin, file descriptor 0), standard output (stdout, 1), and standard error (stderr, 2). A file descriptor is a number identifying an open I/O channel. By default in an interactive terminal these channels commonly point to the terminal, but they may instead point to files or pipes. printf normally writes to stdout. The small redirection >&2 sends its output to descriptor 2; < file supplies input from a file; > file creates or truncates an output file. Use only disposable practice files. Redirection is explored fully in a later chapter.
Practical examples
Run each example separately in Bash 5.2 in a fresh empty practice directory, using default shell options and C locale. Output is shown separately; do not enter it as code.
Separate streams
Expected stdout:
count=2Expected stderr:
using sample dataOverall example exit status: 0
The second command redirects its normal output to stderr.
Read a fixture
Expected stdout:
alphabetaExpected stderr:
No output
Overall example exit status: 0
The external utility cat copies stdin to stdout here. The first command prepares a new local file.
Keep a report clean
printf '%s\n' 'items=4' > report.txt && printf '%s\n' 'report ready' >&2 && cat report.txtExpected stdout:
items=4Expected stderr:
report readyOverall example exit status: 0
Only the result was saved to report.txt. The diagnostic remains separate. The && chain reports readiness only after the write succeeds; it also skips the final read if the diagnostic write fails.
Common mistakes
Stderr is not an exit status. A successful command can print a warning, and a failed command can be silent. Do not mix diagnostic text with machine-readable stdout. Never use > on a file whose content you need to preserve.
Practice
Print count=3 to stdout and using sample data to stderr. Save the normal output to a new practice file and check that the diagnostic is not in it.
Next: printf and echo