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
Replay: real traced execution (multi-file project)
#!/usr/bin/env bash
mode="check"
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="apply"
run_task() {
if [[ "$mode" == "apply" ]]; then
return 0
fi
return 2
}
if run_task; then
outcome="ok"
else
outcome="skip:$?"
fi
echo "$mode:$outcome"
mode ← check
3mode="check"4run_task() {values this stepcheckmodeif run_task; then
9}10if run_task; then11 outcome="ok"values this stepcheckmodeif [[ "$mode" == "apply" ]]; then
4run_task() {5 if [[ "$mode" == "apply" ]]; then6 return 0values this stepcheckmodereturn 2
7 fi8 return 29}outcome ← skip:2
12else13 outcome="skip:$?"14fivalues this stepskip:2outcome2$?echo "$mode:$outcome"
14fi15echo "$mode:$outcome"outputcheck:skip:2values this stepcheckmodeskip:2outcome
mode ← apply
3mode="apply"4run_task() {values this stepapplymodeif run_task; then
9}10if run_task; then11 outcome="ok"values this stepapplymodeif [[ "$mode" == "apply" ]]; then
4run_task() {5 if [[ "$mode" == "apply" ]]; then6 return 0values this stepapplymodereturn 0
5if [[ "$mode" == "apply" ]]; then6 return 07fioutcome ← ok
10if run_task; then11 outcome="ok"12elsevalues this stepokoutcomeecho "$mode:$outcome"
14fi15echo "$mode:$outcome"outputapply:okvalues this stepapplymodeokoutcome
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.