Testing scripts with Bats
Write automated tests for shell scripts with Bats: @test blocks, run, status and output, temp dirs, skip, and sourcing functions. Run on bats-core 1.14.
Exit status and && / || listsStructure and style: main functions and shfmtSafe temporary files and atomic writesLogging, usage messages and exit codes
Testing scripts with Bats
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- A Bats test file is a Bash file where each @test "name" { ... } block is a test. A test passes if every command in it succeeds, so ordinary [ ] and [[ ]] checks are the assertions.
- run COMMAND captures the command's exit status in $status and its output in $output and ${lines[@]}, without the failure stopping the test. Check them afterwards.
- setup runs before each test and teardown after. BATS_TEST_TMPDIR gives each test a fresh temp directory that is removed automatically.
- A script that ends by calling main "$@" unconditionally cannot be sourced for unit tests. Guard it so tests can source it and call its functions, as in the structure lesson.
- Test the contract the caller sees: output on stdout, messages on stderr, and the exit code, including the failure cases.
Why test a script
You have a script that passes its one manual check. Then you change the option parsing, and a week later someone finds that a missing file no longer produces an error. Nothing broke loudly, because nothing was watching.
Tests are a way to remember what you checked by hand. For shell, a test is simply: run the script with some input, and compare the exit status and output with what you expect. Bats (Bash Automated Testing System) gives that a little structure. It finds your tests, runs each in isolation, reports which passed, and exits nonzero if any failed, so a CI job can gate on it.
I used bats-core 1.14.0 on macOS with Bash 5.3, and tested the count500.sh script from the previous lesson.
A test file
A .bats file is Bash with one extra construct, @test:
#!/usr/bin/env bats
bats_require_minimum_version 1.5.0
setup() {
SCRIPT="$BATS_TEST_DIRNAME/../count500.sh"
LOG="$BATS_TEST_DIRNAME/../fx/logs/access.log"
}
@test "counts 500s in one file" {
run "$SCRIPT" "$LOG"
[ "$status" -eq 0 ]
[ "$output" = "24 $LOG" ]
}
@test "no arguments is a usage error (64)" {
run "$SCRIPT"
[ "$status" -eq 64 ]
[[ $output == *"no files given"* ]]
}
Each @test block is a function. A test passes if every command in it succeeds, and that is how assertions work: [ "$status" -eq 0 ] fails the test if the condition is false, because a failing command ends the block. (Bats runs tests with set -e behaviour, with the details in its documentation.) There is no assertion library required. The checks are the [ ] and [[ ]] you know from conditionals.
run
Calling the script directly would be a problem for any test of a failure: a nonzero status ends the test on that line. run is the answer. It executes the command, never fails itself, and stores:
$status, the exit code,$output, stdout and stderr combined,${lines[@]}, the same, split by line.
$ bats test
1..7
ok 1 counts 500s in one file
ok 2 -h prints usage and exits 0
ok 3 no arguments is a usage error (64)
ok 4 unreadable file warns and exits 1 but still counts the rest
ok 5 an empty log counts zero
...
The output is TAP, a simple line format any CI can parse, and it applies the exit status rule: Bats exits 0 only if everything passed.
Because run merges stdout and stderr, separate them when the difference matters. run --separate-stderr puts the error text in $stderr. My test of the unreadable-file case used it:
@test "unreadable file warns and exits 1 but still counts the rest" {
run --separate-stderr "$SCRIPT" "$BATS_TEST_TMPDIR/missing" "$LOG"
[ "$status" -eq 1 ]
[[ $stderr == *"cannot read"* ]]
[ "$output" = "24 $LOG" ]
}
That test checks the whole contract from the last lesson: data on stdout, warnings on stderr, and a nonzero status.
Flags on run need Bats 1.5 or newer. Without bats_require_minimum_version 1.5.0, my first run printed a BW02 warning saying so. And a run of a command that does not exist gives status 127. Asserting it works, but Bats warns (BW01) and suggests run -127 so the expectation is explicit.
Temp files, skip, and failures
BATS_TEST_TMPDIR is a directory made fresh for each test and deleted afterwards. After running my tests there were no bats-run-* leftovers in the temp area:
@test "an empty log counts zero" {
: > "$BATS_TEST_TMPDIR/empty.log"
run "$SCRIPT" "$BATS_TEST_TMPDIR/empty.log"
[ "$status" -eq 0 ]
[ "$output" = "0 $BATS_TEST_TMPDIR/empty.log" ]
}
It builds on the temporary file lesson. skip "reason" marks a test as not yet applicable:
ok 7 not yet written # skip needs a fixture with a 404 section
I added one wrong expectation on purpose to see how failure looks:
# got: 24 ./test/../fx/logs/access.log
not ok 6 a deliberately wrong expectation
# (in test file test/count500.bats, line 45)
# `[ "$output" = "25 $LOG" ]' failed
exit=1
Bats names the test, the line and the command, but with a bare [ ] it does not print the values compared. The line starting with # got: came from a diagnostic I added: echo "# got: $output" >&3. File descriptor 3 is Bats’ channel back to the report, and lines beginning with # are shown as comments. A helper library, bats-assert, prints expected and actual values, and it was not installed here, so I did not run it.
Unit tests: sourcing the functions
Running the whole script tests it from outside. To test one function, load the file and call it. That only works if sourcing does not run main, which is what the BASH_SOURCE guard from the structure lesson is for. With that guard in tidy.sh:
setup() {
source "$BATS_TEST_DIRNAME/../tidy.sh"
LOG="$BATS_TEST_DIRNAME/../fx/logs/access.log"
}
@test "count_errors prints a number" {
run count_errors "$LOG"
[ "$status" -eq 0 ]
[ "$output" = 24 ]
}
@test "count_errors fails on a missing file" {
run count_errors "$BATS_TEST_TMPDIR/nope"
[ "$status" -eq 1 ]
}
1..2
ok 1 count_errors prints a number
ok 2 count_errors fails on a missing file
Both ran. count500.sh as written calls main "$@" at the bottom with no guard, so it can only be tested from the outside, as above.
What to test
The caller’s view: normal input, each error path, and the exit code for each. Not every line. Put bats test in your CI job or a Git hook, alongside shellcheck and shfmt -d.
About the video
“Test-Driven Development (TDD) Tutorial: Unit Testing Bash Scripts with Bats on Rocky Linux 10” is a 23-minute 26-second video from theurbanpenguin (Andrew Mallett), published July 2025. The description says it teaches writing tests before code and using Bats to build and run unit tests for scripts. It has no chapters, and the page offered no caption track information, so I could not read a transcript and judged the language from the channel and the English title and description. Rocky Linux is a Linux distribution, so install steps will differ on a Mac. Install with brew install bats-core instead, which I did not run here, because Bats was already installed.
Where this fits
That completes the roadmap: from what a shell is, through quoting and scripting, to scripts that are formatted, safe, honest about failure and tested. From here, git-hooks can run the checks on every commit, and the devops roadmap covers running them in CI.
Check yourself
In a Bats test, why use run instead of calling the script directly?
A direct call that fails stops the test at that line with no chance to check anything. run records status and output so you can assert the failure was the expected one.
How do you assert that a script exited with the usage-error code 64?
run ./script, then [ "$status" -eq 64 ]. In Bats 1.5 and later you can also write run -64 ./script.
Where should a test create files it needs, and how are they cleaned up?
In $BATS_TEST_TMPDIR. Bats makes the directory per test and removes it afterwards, so tests do not leak files or interfere with each other.
A test fails and shows only the failed line. How do you see the actual output?
Print it to file descriptor 3, which Bats shows in the report, for example echo "# got: $output" >&3, or use the bats-assert helper library.
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.