Interview Prep/Shell Scripting/Functions, exit codes, strict mode and traps

What is the `RETURN` trap and the `DEBUG` trap used for?

AdvancedConceptFunctions, exit codes, strict mode and traps
Answer

DEBUG runs before every simple command, RETURN after a function or sourced file returns. They are used for tracing and tooling, rarely in production scripts.

trap 'echo "+ $BASH_COMMAND" >&2' DEBUG       # poor man's tracer
f() { trap 'echo "leaving f"' RETURN; ...; }  # per-function cleanup

By default, functions do not inherit DEBUG and RETURN traps; set -T (functrace) changes that. DEBUG traps are expensive and slow a script noticeably.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Functions, exit codes, strict mode and traps