Interview Prep/Shell Scripting/Troubleshooting: strict mode, exit codes, pipelines and traps

`result=$(compute_checksums; echo done)` returns `done` even when `compute_checksums` fails, despite `set -e`.

AdvancedTroubleshootingTroubleshooting: strict mode, exit codes, pipelines and traps
Answer

Likely causes → Command substitutions run in a subshell, and Bash clears errexit inside them by default (outside POSIX mode). The failure inside is ignored, the last command (echo) succeeds, and the substitution's status is 0.

Diagnose →

bash -c 'set -e; x=$(false; echo ok); echo "x=$x"'                              # x=ok
bash -c 'set -e; shopt -s inherit_errexit; x=$(false; echo ok); echo "x=$x"'    # exits 1

Fix → Turn on inherit_errexit (Bash 4.4+) next to the strict header, and keep one command per substitution:

set -Eeuo pipefail
shopt -s inherit_errexit
sums=$(compute_checksums)       # status of compute_checksums propagates to the assignment

Prevent → Avoid multi-command substitutions; if a substitution must do several things, make it a function that returns its own errors explicitly.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Troubleshooting: strict mode, exit codes, pipelines and traps