Decisions and Status
If Tests
Choosing a Path
An if statement runs one block when a test succeeds and another block when it fails.
Program
Play the script to watch the numeric test choose the pass branch.
if_tests.sh
Replay: real traced execution (multi-file project)
#!/usr/bin/env bash
score=82
if (( score >= 70 )); then
grade="pass"
else
grade="retry"
fi
echo "$grade"
score ← 82
3score=824if (( score >= 70 )); thenvalues this step82scorepath ← then
3score=824if (( score >= 70 )); then5 grade="pass"values this stepthenpath82scoregrade ← pass
4if (( score >= 70 )); then5 grade="pass"6elsevalues this steppassgradeecho "$grade"
8fi9echo "$grade"outputpassvalues this steppassgrade
Choose the Branch
scorestarts at82.(( score >= 70 ))runs as a command.- A true arithmetic test chooses the
thenbranch. - A false arithmetic test chooses the
elsebranch. | Test result | Branch |grade| | --- | --- | --- | | true |then|pass| | false |else|retry|
if
`if` uses a command or test status to choose which block runs.
numeric test
`(( ... ))` is an arithmetic command; zero is false and nonzero is true.
Exercise: if_tests.sh
Use an if test to label scores 70 or higher as pass and lower scores as retry