CodeRigor

FREE LESSON

Exit status, tests & conditions

Use status as control flow, distinguish string and arithmetic tests, and validate numeric input before arithmetic.

Before this lesson, complete bash-quoting.

This course runs GNU Bash with ordinary GNU text tools in a fresh Linux sandbox.

In Bash, an if condition runs a command and tests its exit status: zero selects the then branch, while a nonzero status selects a later branch or else. Output and status are separate channels. A command can print useful output and still fail. Capture $? immediately when you need it, because the next command replaces it.

Status drives an if
start / 3
Status drives an if

Apply the contract

Use [[ ... ]] for shell string and file predicates, and (( ... )) for arithmetic. Within double brackets, -n asks whether a string is nonempty; it says nothing about its numeric value. The < operator there compares strings, so it is the wrong choice for a numeric threshold. An arithmetic condition succeeds when its expression is nonzero and fails when it is zero. This can be surprising for an increment starting from zero.

Three different predicates
start / 3
Three different predicates
Bash
for value in -1 0 2 10; do
  if (( value < 0 )); then printf 'negative\n'; else printf 'nonnegative\n'; fi
done
if false; then printf 'unexpected\n'; else printf 'failure is a branch\n'; fi

Reason about the edge cases

Validate external text before letting arithmetic interpret it. Bash arithmetic accepts expressions and numeral prefixes, which is broader than this lab's decimal input grammar. The regular expression in the contract allows an optional minus and canonical decimal digits. Reject leading-zero forms such as 08 before comparison. The lab bounds valid inputs to a small magnitude, so representation overflow is outside the exercise. Classify negative, zero and positive values in that order; then partition positive values at ten. Keep a successful overall script status even when an argument is classified invalid.

Classify validated input
start / 3
Classify validated input

Practice

Classify each argument as invalid, negative, zero, small (1 through 9), or large (10 or more), one line each. Valid inputs use canonical decimal notation: optional minus and either 0 or a nonzero digit followed by digits. Valid magnitudes are at most 1000. Values such as 08, +3, empty strings and expressions are invalid. Exit successfully after classifying all arguments.

Run sample starts again from the first public fixture and grants no mastery evidence. Submit checks all fixtures, including edge cases. Read the specification before editing; the bug and fill phases share the build’s contract. Flashcards reinforce recall on a separate schedule.

Watch & read

Free lectures, talks and readings that cover this skill from another angle. All resources →

Free shell scripting foundation. Use the authored lesson and GNU Bash manual for this lab’s precise argument, status and process contract.