Bash functions return status codes, not rich values. That makes functions useful inside if statements.

Program

Play the script to see is_even return success and choose the then branch.

return_status.sh
Replay: real traced execution (multi-file project)
#!/usr/bin/env bash

is_even() {
  local value="$1"
  (( value % 2 == 0 ))
}

number=8
if is_even "$number"; then
  echo "even"
else
  echo "odd"
fi
  1. is_even ← defined

    3is_even() {4  local value="$1"
    values this stepdefinedis_even
  2. number ← 8

    8number=89if is_even "$number"; then
    values this step8number
  3. call ← is_even 8

    8number=89if is_even "$number"; then10  echo "even"
    values this stepis_even 8call8number
  4. value ← 8

    3is_even() {4  local value="$1"5  (( value % 2 == 0 ))
    values this step8value8$1
  5. $? ← 0

    4  local value="$1"5  (( value % 2 == 0 ))6}
    values this step0$?8value
  6. path ← then

    8number=89if is_even "$number"; then10  echo "even"
    values this stepthenpath0$?
  7. echo "even"

    9if is_even "$number"; then10  echo "even"11else
    outputeven

Follow the Status

  1. is_even() is defined as a test function.
  2. number is set to 8.
  3. The call is_even 8 gives the function value=8.
  4. The arithmetic test value % 2 == 0 succeeds with status 0.
  5. The if uses the then path and prints even. | step | visible state | | --- | --- | | input number | 8 | | function value | 8 | | test | 8 % 2 == 0 | | status | 0 | | branch output | even |
return status A function's status is the status of its last command unless it calls `return`.
predicate A predicate command answers a yes/no question through its exit status.

Exercise: return_status.sh

Reproduce even, then identify the arithmetic test result and the branch chosen by status 0.