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.

mode
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"
  1. mode ← check

    3mode="check"4run_task() {
    values this stepcheckmode
  2. if run_task; then

    9}10if run_task; then11    outcome="ok"
    values this stepcheckmode
  3. if [[ "$mode" == "apply" ]]; then

    4run_task() {5    if [[ "$mode" == "apply" ]]; then6        return 0
    values this stepcheckmode
  4. return 2

    7    fi8    return 29}
  5. outcome ← skip:2

    12else13    outcome="skip:$?"14fi
    values this stepskip:2outcome2$?
  6. echo "$mode:$outcome"

    14fi15echo "$mode:$outcome"
    outputcheck:skip:2
    values this stepcheckmodeskip:2outcome
  1. mode ← apply

    3mode="apply"4run_task() {
    values this stepapplymode
  2. if run_task; then

    9}10if run_task; then11    outcome="ok"
    values this stepapplymode
  3. if [[ "$mode" == "apply" ]]; then

    4run_task() {5    if [[ "$mode" == "apply" ]]; then6        return 0
    values this stepapplymode
  4. return 0

    5if [[ "$mode" == "apply" ]]; then6    return 07fi
  5. outcome ← ok

    10if run_task; then11    outcome="ok"12else
    values this stepokoutcome
  6. echo "$mode:$outcome"

    14fi15echo "$mode:$outcome"
    outputapply:ok
    values 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.