🎓 A1Learner
🔍
0 of 45 lessons completed

Bash Test Functions

Test functions are small functions that check one behaviour and return success or failure. A runner calls each test function and counts how many passed and failed.

A test function returns pass or fail

The function compares a sum with the expected value. Its return status is the test result.

test_add() {
  [ $((2 + 3)) -eq 5 ]
}
if test_add; then
  echo "test_add: pass"
else
  echo "test_add: fail"
fi

A runner counts results

The runner calls each test and counts passes and failures. The failing subtraction test raises the fail count.

passed=0
failed=0
run() {
  if "$@"; then
    passed=$((passed + 1))
  else
    failed=$((failed + 1))
  fi
}
test_add() { [ $((2 + 3)) -eq 5 ]; }
test_sub() { [ $((5 - 2)) -eq 4 ]; }
run test_add
run test_sub
echo "$passed passed, $failed failed"

A test can check a file

Some behaviour lives in a file, not in arithmetic. This test searches the file for the expected word.

printf 'hello
' > msg.txt
test_greeting() { grep -q 'hello' msg.txt; }
if test_greeting; then
  echo "test_greeting: pass"
else
  echo "test_greeting: fail"
fi

Example

passed=0
failed=0
run() {
  if "$@"; then
    passed=$((passed + 1))
  else
    failed=$((failed + 1))
  fi
}
test_add() { [ $((2 + 3)) -eq 5 ]; }
test_sub() { [ $((5 - 2)) -eq 4 ]; }
test_upper() { [ "$(printf 'abc' | tr 'a-z' 'A-Z')" = "ABC" ]; }
run test_add
run test_sub
run test_upper
echo "$passed passed, $failed failed"

Key points

  • Return status: a test function returns 0 for pass and non-zero for fail.
  • One behaviour: each test function checks a single fact, so a failure points at one thing.
  • Runner: a runner function calls each test and adds one to a pass or fail count.
  • No set -e: a failing test must not abort the runner before later tests run.
  • Summary: the runner prints one final count line, such as 2 passed, 1 failed.
  • Honest limit: a passing test proves only the checked fact, not the whole script.

In this example, a runner counts results for three test functions. Each test checks one fact: a sum, a difference, and an uppercase conversion. The runner calls each test in turn and adds one to the pass or fail count. The final line shows two passes and one failure.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What should a test function return when the checked behaviour is correct?