Write a Bats test
Write a Bats test file with @test blocks, run it with the bats command, and read the TAP output. A test passes when every command in it exits 0.
You want to test a shell function the way you test code in any other language, with named cases and a pass or fail result.
cat > test.bats <<'EOF'
@test "addition works" {
result=$((2 + 3))
[ "$result" -eq 5 ]
}
@test "grep finds a word" {
echo "hello world" | grep -q world
}
@test "this one fails" {
[ "$((2 + 2))" -eq 5 ]
}
EOF
bats test.bats
echo "exit: $?"1..3
ok 1 addition works
ok 2 grep finds a word
not ok 3 this one fails
# (in test file test.bats, line 11)
# `[ "$((2 + 2))" -eq 5 ]' failed
exit: 1Each @test block becomes a shell function that runs with set -e in effect, so the first command that returns non-zero fails the test, which is why a bare [ ... ] is an assertion. Bats prints the TAP format, a plan line followed by an ok or not ok for each case, and for a failure it names the file, the line and the command that failed.
The exit status of bats is 1 when any test fails, so it works as a CI step. A command that fails inside an if or after || does not trip set -e, so write assertions as plain commands. The output here is from Bats 1.8.2, and the @test syntax needs the bats runner and is not valid Bash on its own.