Understanding the Stream Duplication Challenge

In Bash scripting, standard output (stdout, File Descriptor 1) and standard error (stderr, File Descriptor 2) operate as separate streams. A common requirement when logging or monitoring execution is to merge stderr into stdout so you have a single unified output stream, while simultaneously keeping stderr intact so error listeners or log aggregators receive errors independently.

Specifically, the goal is to achieve:

  • stdout stream: Contains all original stdout lines interleaved with original stderr lines.
  • stderr stream: Contains only original stderr lines.

The Solution: Bash Process Substitution with tee

If you are using Bash, the cleanest and most efficient approach utilizes process substitution (>(...)) combined with tee: