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"
  1. score ← 82

    3score=824if (( score >= 70 )); then
    values this step82score
  2. path ← then

    3score=824if (( score >= 70 )); then5  grade="pass"
    values this stepthenpath82score
  3. grade ← pass

    4if (( score >= 70 )); then5  grade="pass"6else
    values this steppassgrade
  4. echo "$grade"

    8fi9echo "$grade"
    outputpass
    values this steppassgrade

Choose the Branch

  1. score starts at 82.
  2. (( score >= 70 )) runs as a command.
  3. A true arithmetic test chooses the then branch.
  4. A false arithmetic test chooses the else branch. | 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