Functions and Scripts
Return Status
Functions as Tests
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
is_even ← defined
3is_even() {4 local value="$1"values this stepdefinedis_evennumber ← 8
8number=89if is_even "$number"; thenvalues this step8numbercall ← is_even 8
8number=89if is_even "$number"; then10 echo "even"values this stepis_even 8call8numbervalue ← 8
3is_even() {4 local value="$1"5 (( value % 2 == 0 ))values this step8value8$1$? ← 0
4 local value="$1"5 (( value % 2 == 0 ))6}values this step0$?8valuepath ← then
8number=89if is_even "$number"; then10 echo "even"values this stepthenpath0$?echo "even"
9if is_even "$number"; then10 echo "even"11elseoutputeven
Follow the Status
is_even()is defined as a test function.numberis set to8.- The call
is_even 8gives the functionvalue=8. - The arithmetic test
value % 2 == 0succeeds with status0. - The
ifuses thethenpath and printseven. | 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.