Interview Prep/Shell Scripting/Arguments, I/O, here-docs, process substitution and subshells

Why is `cmd 2>&1 > file` different from `cmd > file 2>&1`?

AdvancedConceptArguments, I/O, here-docs, process substitution and subshells
Answer

Redirections are processed left to right, and 2>&1 copies wherever fd 1 points at that moment.

  • > file 2>&1: fd 1 → file, then fd 2 → (fd 1 = file). Both go to the file.
  • 2>&1 > file: fd 2 → (fd 1 = terminal), then fd 1 → file. Errors still go to the terminal.

The second form is occasionally useful on purpose: out=$(cmd 2>&1 >/dev/null) captures only stderr.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Arguments, I/O, here-docs, process substitution and subshells