Redirection order matters
Bash applies redirections from left to right. Draw a table with rows for descriptors 1 and 2 and update it one operator at a time. Initially both may point to a terminal, but they can also be inherited files or pipes. In report > both.log 2>&1, first descriptor 1 points to the file, then 2 duplicates that destination. In report 2>&1 > data.log, descriptor 2 copies the original destination of 1, and only then 1 moves to the file. The second operator does not move 2. A redirection can also fail after an earlier one already created or truncated a file. A pipeline is connected before the command’s own explicit redirections, so an explicit output file can override a pipe’s output path. Test these cases with fixed functions and disposable files; do not assume the destination is always the terminal. A duplicated descriptor keeps the same underlying destination even after the original descriptor is redirected or closed. The final example demonstrates routing, not end-to-end success: without pipefail, a successful consumer can hide a failed producer.
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.
Redirect then duplicate
report() { printf 'out\n'; printf 'err\n' >&2; }report > both.log 2>&1printf 'file:\n'; cat both.logExpected stdout:
file:outerrBoth descriptors refer to the same opened file.
Duplicate then redirect
report() { printf 'out\n'; printf 'err\n' >&2; }report 2>&1 > data.logprintf 'file:\n'; cat data.logExpected stdout:
errfile:outThe diagnostic appears on the original stdout; data.log contains only out.
Explicit output wins over a pipe
printf '%s\n' payload > captured.txt | catprintf 'file: '; cat captured.txtExpected stdout:
file: payloadThe pipe consumer sees EOF without the payload; the explicit file gets it.
Common mistakes
Do not read redirections as an unordered list or assume 2>&1 always means both streams go to the last file. Avoid opening the same file independently for both streams because offsets and truncation can interact.
Practice
For a function writing out and err, predict the destinations after each operator in both orders. Run each into new files, then use cat to verify. Explain where err goes when original stdout is captured.
Next: Here documents and here strings