Shell Library Design
Status Return
Report Failure
Library functions should return a status that callers can branch on. The caller can then turn the status into a clear outcome message.
Program
Play the script to choose the task mode and see how the caller handles the return status.
library_status_return.sh
#!/usr/bin/env bash
mode=
run_task() {
if [[ "$mode" == "apply" ]]; then
return 0
fi
return 2
}
if run_task; then
outcome="ok"
else
outcome="skip:$?"
fi
echo "$mode:$outcome"
#!/usr/bin/env bash
mode=
run_task() {
if [[ "$mode" == "apply" ]]; then
return 0
fi
return 2
}
if run_task; then
outcome="ok"
else
outcome="skip:$?"
fi
echo "$mode:$outcome"
return status
A function returns a numeric status that the caller can test.
caller branch
The caller decides how to handle success or failure.
status message
Turning a numeric status into a message makes failures easier to inspect.