Functions and sourced helpers
Reuse a supplied helper and keep function-local values scoped.
Give a useful operation a name
A Bash function groups commands and accepts its own positional arguments. describe() { ...; } defines a function; describe web calls it. return sets an exit status, not a string result. To return text, print it and capture that output with command substitution.
Use local inside a function for working variables. Avoid combining a declaration and a fallible substitution in one command: local result=$(command) can hide the command’s failing status. Declare first, then assign and check the assignment.
Sourcing is execution in this shell
. ./helpers.sh reads and executes another file in the current shell. Its functions and assignments remain available afterward. This differs from bash ./helpers.sh, which runs a child process whose variables cannot update the parent.
Source only a helper you trust. A helper file is executable code, even when its name sounds like configuration. The supplied helper is part of this lesson’s fictional reporting tool. Keep main.sh as the single edited file; the exercise checks that your code calls the helper rather than copying a hard-coded answer.
. ./helpers.sh || exit 1
label=$(severity_label 2) || exit 1
printf 'Result: %s\n' "$label"
Put it into practice.
Source the supplied `helpers.sh`. For argument 1 (default `2`), call its `severity_label` function and capture the returned text. Define a function named `report` that prints `Severity: <label>` plus newline. Call report with the supplied code, preserve helper errors, and exit nonzero if the helper rejects the code.
See an explained solution
. ./helpers.sh || exit 1
report() {
local label
label=$(severity_label "$1") || return 1
printf 'Severity: %s\n' "$label"
}
report "${1:-2}"
The helper determines the label. The report function composes it into a message and propagates a failed lookup instead of printing a misleading success.