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

How does `exec 2>>` or `BASH_XTRACEFD` help separate debug output from normal output?

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

set -x writes traces to stderr by default, mixing them with real errors. Bash can send trace output to a dedicated fd:

exec {xfd}>>/var/log/deploy/trace.log
BASH_XTRACEFD=$xfd
PS4='+ ${BASH_SOURCE##*/}:${LINENO}:${FUNCNAME[0]:-main}: '
set -x

Now stderr contains only real errors (and goes to the alerting pipeline), while the trace file has every command with file, line and function. Remember that traces include expanded secrets; wrap sensitive sections in set +x and set -x.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

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