Debugging Bash Like a Sire
10 months ago
- #Bash
- #Debugging
- #Scripting
- Bash has limitations in error handling and data structures, leading to defensive scripting.
- Common Bash debugging flags: `set -euxo pipefail` for exiting on errors, undefined variables, printing evaluations, and failing pipes.
- Debugging flags can be inconsistent across Bash versions and may not clearly indicate the problem's location or nature.
- Custom logging functions (`log::info`, `log::level_is_active`, `log::_write_log`) enhance debugging with formatted logs and level checks.
- Logging functions use `BASH_SOURCE` and `FUNCNAME` to track the source file and function name, improving traceability.
- Redirecting logs to `stderr` (`>&2`) prevents confusion with script output intended for actual values.
- Example log format: `INFO [23.12.22 18:34:09] [github.sh - github::bootstrap]: Bootstrap has started`.
- Extended error handling with `log::error` includes stack traces for better debugging.
- Using `trap 'log::error "An error has occurred"' ERR` ensures errors are logged even if the script exits unexpectedly.