Bash scripts are brittle – simple error handling in bash
3 months ago
- #devops
- #error-handling
- #bash
- Bash scripts are commonly used as system glue in CI/CD pipelines or CronJobs.
- Default behavior in bash is to continue executing commands even if one fails, unlike other programming languages.
- The `-e` option in bash can be used to exit immediately if a command fails.
- Exit codes in bash: 0 means success, any other number indicates an error.
- Error handling techniques include `if else` statements, logical operators (`&&`, `||`), and the `trap` command.
- Pipes (`|`) in bash can hide command failures unless `pipefail` is enabled.
- Undefined variables can cause issues; use `-u` to treat unset variables as errors.
- Combining options like `set -eEuo pipefail` provides robust error handling.
- Alerting on errors is crucial, especially for cron jobs, using tools like Slack webhooks or Notifox CLI.