Bats and shell test design
A test has a defined input, an expected outcome and an assertion. Bats is a Bash-oriented test framework. In a compatible Bats version, run invokes a command and records its status and output in variables such as $status and $output; the helper itself normally succeeds so that the test can assert a nonzero command result. run --separate-stderr also exposes $stderr (documented in Bats 1.8.1). Captured text is not a byte-exact binary comparison. The following optional example belongs in greet.bats next to a greet.sh containing printf 'Hello, %s\n' "$1". It is DOCUMENTED / NOT RUN because Bats is absent.
@test "name with spaces" { run --separate-stderr bash "$BATS_TEST_DIRNAME/greet.sh" "Ada Lovelace" [ "$status" -eq 0 ] [ "$output" = "Hello, Ada Lovelace" ] [ -z "$stderr" ]}Run bats greet.bats only when installed. Bats syntax is not an ordinary bash -n input. The following Bash-native tests independently assert the status, output and files; this is not Bats execution. For cmp, status 0 means equal, 1 means different, and a greater status indicates trouble. A negative comparison test must require status 1 rather than accepting every failure.
Practical examples
Run each example as a separate script in a fresh noninteractive Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Assert a success contract
greet() { printf 'Hello, %s\n' "$1"; }greet 'Ada Lovelace' > actual.txt 2> err.txtrc=$?printf 'Hello, Ada Lovelace\n' > expected.txt || exit 1[[ $rc == 0 && ! -s err.txt ]] && cmp -s actual.txt expected.txt || exit 1printf 'PASS\n' Expected stdout:
PASSThe exact output file, status and empty stderr are checked.
Assert an expected failure
greet() { if [[ $# != 1 || -z ${1-} ]]; then printf 'name required\n' >&2 return 2 fi printf 'Hello, %s\n' "$1"}greet '' > actual.txt 2> err.txtrc=$?printf 'name required\n' > expected.txt || exit 1[[ $rc == 2 && ! -s actual.txt ]] && cmp -s err.txt expected.txt || exit 1printf 'PASS\n' Expected stdout:
PASSA program failure is a passing test when it matches the contract.
Reject wrong output
printf 'Hello\n\n' > actual.txt || exit 1printf 'Hello\n' > expected.txt || exit 1if cmp -s actual.txt expected.txt; then printf 'unexpected pass\n' exit 1else rc=$? [[ $rc == 1 ]] || exit 1 printf 'extra newline rejected\n'fiExpected stdout:
extra newline rejectedComparing files detects a trailing newline difference.
Common mistakes
Do not assert only stdout if the command can fail. Avoid command substitution for byte-exact output because it removes trailing newlines. A test with no meaningful assertions can pass despite a bug.
Practice
Design a greeting CLI test matrix for an ordinary name, a name containing spaces, an empty argument and zero arguments. Define its status, stdout and stderr for every case before implementing the tests.
Next: Fixtures and regression testing