Redirect stderr and duplicate descriptors
Separate diagnostics from data by directing descriptor 2 to its own destination. cmd 2> errors.log affects stderr only; cmd > data.txt 2> errors.log separates both. n>&m duplicates an already-open output descriptor m onto n, and n<&m does the analogous operation for input. Thus printf ... >&2 sends the ordinary output to the current stderr destination. Duplication is a snapshot of the descriptor mapping at that point, not a permanent link between descriptor numbers. Bash offers &> file for both standard streams and &>> file for appending both. Prefer > file 2>&1 and >> file 2>&1 when targeting traditional portable shell syntax. A diagnostic does not automatically make the command fail; inspect its status separately. Duplicated descriptors referring to one open file description share its current offset; independently opening the same path does not necessarily share that offset. In example 3, closing descriptor 3 after both reads does not undo the bytes consumed.
Practical examples
Run each example separately in a fresh Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Separate the streams
report() { printf '%s\n' data; printf '%s\n' diagnostic >&2; }report > data.txt 2> errors.logprintf 'data: '; cat data.txtprintf 'errors: '; cat errors.logExpected stdout:
data: dataerrors: diagnosticEach stream has its own file.
Merge and append both streams
report() { printf '%s\n' data; printf '%s\n' note >&2; }report &> combined.logreport &>> combined.logcat combined.logExpected stdout:
datanotedatanoteThe first call creates the combined file; the second appends.
Duplicate an input descriptor
printf 'first\nsecond\n' > input.txt || exit 1exec 3<input.txt || exit 1IFS= read -r a 0<&3 || exit 1IFS= read -r b 0<&3 || exit 1exec 3<&- || exit 1printf '%s %s\n' "$a" "$b"Expected stdout:
first secondThe duplicated descriptor shares the underlying open file offset.
Common mistakes
2 > file passes a word 2 as an argument and redirects stdout, not stderr. Do not mix data and logs if another program parses stdout.
Practice
Define a function emitting two data lines and one diagnostic. Save stdout and stderr separately, inspect both, then append a second invocation to one combined file. Predict every line.
Next: Redirection order matters