04 / DECISIONS AND REPETITION · LESSON 13

Tests and conditionals

Validate a numeric value before choosing a threshold-based action.

13 min · learn at your pace

Commands choose branches

An if statement runs a command and branches on its exit status. [ ... ] is a command too: spaces around its arguments and the closing bracket matter. [ "$free" -lt 20 ] compares integers. [ "$name" = 'web' ] compares strings. Quote data so empty values still occupy one argument.

Bash also provides [[ ... ]], which has different parsing rules and useful Bash-specific operators. It is not interchangeable with POSIX test syntax. Start with simple, explicit tests that you can explain.

Validate before arithmetic

A number-looking string may contain invalid characters or be outside the allowed range. Use a case pattern to reject nondigits, then bound its length and value. Bash arithmetic interprets a leading zero as octal; 10# states decimal explicitly, so 008 means eight. This form is available in Bash 3.2.

Thresholds are part of a tool’s contract. Test the values immediately below, at and above each boundary. Distinguish an invalid input from a valid value that happens to require attention: a warning classification need not mean the script itself failed.

Try an example.sh
free=18
if [ "$free" -lt 20 ]; then
    printf 'Review capacity\n'
else
    printf 'Capacity is healthy\n'
fi
YOUR TURN

Put it into practice.

Read argument 1, defaulting to `20`, as a decimal integer from 0 to 100 (at most three digits). Print `critical` below 10, `warning` from 10 through 19, or `healthy` from 20 upward. Accept leading zeros. Invalid values must print `Invalid percentage` to stderr and exit 2, with no stdout.

See an explained solution
One way to solve it.sh
value=${1-20}
invalid() { printf 'Invalid percentage\n' >&2; exit 2; }
case "$value" in ''|*[!0-9]*) invalid ;; esac
[ "${#value}" -le 3 ] || invalid
value=$((10#$value))
[ "$value" -le 100 ] || invalid
if [ "$value" -lt 10 ]; then printf 'critical\n'
elif [ "$value" -lt 20 ]; then printf 'warning\n'
else printf 'healthy\n'
fi

Validation keeps malformed text out of arithmetic. Ordered comparisons make 10 warning and 20 healthy, with a distinct error status for invalid input.