How do you write a reusable `die` function, and why send errors to stderr?
BeginnerConceptFunctions, exit codes, strict mode and traps
Answer
die() {
printf 'ERROR: %s\n' "$*" >&2
exit "${2:-1}"
}
[[ -f $config ]] || die "config not found: $config"
stdout is for data the caller may capture or pipe (ips=$(get_ips)); stderr is for humans and logs. If errors go to stdout, they end up inside variables and pipelines, and cron/systemd cannot separate them.
More on Functions, exit codes, strict mode and traps
How do you define a function, pass arguments and return a value?BeginnerWhat does `local` do, and what is dynamic scoping?AdvancedWhy is `local out=$(cmd)` a problem under `set -e`?AdvancedWhat are the conventional exit codes, and what do 126, 127, 130, 137 and 143 mean?BeginnerWhat does `set -e` do, and where does it NOT cause an exit?AdvancedExplain `set -euo pipefail` line by line, and add the `-E` flag.Beginner