BASH / CHAPTER 08
Redirections and separate output channels
IntermediateKeep machine-readable results separate from diagnostics.
By the end of this chapter
- Distinguish stdout and stderr
- Trace redirection order
- Prevent diagnostics from contaminating data output
The idea
Commands normally write results to standard output and diagnostics to standard error. Keeping those channels separate lets a caller capture or pipe data without accidentally treating an error message as a record. The redirection >&2 sends output to the current standard-error destination. Redirecting stderr to a file or to /dev/null changes that channel without automatically changing stdout.
Redirections are processed from left to right. Duplicating one file descriptor records its current destination, so command >out 2>&1 differs from command 2>&1 >out. The former sends both streams to the file; the latter leaves stderr pointing at the previous stdout destination. Avoid casually merging streams when downstream code expects a strict data format, and define whether a failure should still produce partial normal output.
{ printf 'value\n'; printf 'warning\n' >&2; } 2>/dev/nullvalue
Only the diagnostic channel is discarded; the normal output remains visible.
Try it yourself
Write a function that returns one result line on stdout and a validation error on stderr with nonzero status.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING