Testing Bash Scripts with Bats
Bats, the Bash Automated Testing System, is a testing framework for shell scripts. A Bats test is a small Bash function that runs a command and checks the result: the exit status, the output, the files the command created. Bats runs every test in isolation, reports which ones passed and which failed, and exits with a non-zero status if anything failed, so the tests can guard every change in a CI pipeline.
Shell scripts are often treated as too small or too simple to test, and they are exactly the code that breaks quietly: a backup script that stopped backing up, a deployment script that no longer rolls back. Automated tests turn the checks you would do by hand after each change into a command that takes seconds. This lesson explains how Bats works, how to write tests for a script's output, exit status, error messages and files, how to test individual functions, and how to run the tests locally and in CI. The actively maintained version of the project is bats-core, the successor of the original Bats, and everything in this lesson refers to it.
Installing Bats
Bats is itself written in Bash and can be installed in several ways:
sudo apt install bats # Debian, Ubuntu
brew install bats-core # macOS with Homebrew
npm install -g bats # anywhere Node.js is available
# from source, any system: installs into /usr/local/bin and /usr/local/libexec
git clone https://github.com/bats-core/bats-core.git
cd bats-core && sudo ./install.sh /usr/local
Distribution packages can lag behind, so check the version with bats --version. Some features in this lesson, such as run -N and --separate-stderr, require version 1.5.0 or later.
Many projects add bats-core to the repository itself as a Git submodule, for example under test/bats, and run it as test/bats/bin/bats test. Every developer and every CI job then uses exactly the same version without installing anything.
The Script Under Test
The examples in this lesson test bin/bump.sh, a small tool that increases a semantic version number of the form MAJOR.MINOR.PATCH. It can print a bumped version or update a version file in place:
#!/usr/bin/env bash
#
# bump.sh - increase a semantic version number (MAJOR.MINOR.PATCH)
#
# Usage: bump.sh major|minor|patch VERSION print the bumped version
# bump.sh major|minor|patch -f FILE bump the version stored in FILE, in place
#
# Exit status: 0 success, 2 usage error or invalid version
usage() { sed -n '5,6s/^# \{0,1\}//p' "${BASH_SOURCE[0]}" >&2; exit 2; }
# bump_version PART VERSION: print VERSION with PART increased and the lower parts reset
bump_version() {
local part=$1 version=${2#v} major minor patch
if [[ ! $version =~ ^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$ ]]; then
echo "bump.sh: invalid version: '$2'" >&2
return 2
fi
major=${BASH_REMATCH[1]} minor=${BASH_REMATCH[2]} patch=${BASH_REMATCH[3]}
case $part in
major) echo "$(( major + 1 )).0.0" ;;
minor) echo "$major.$(( minor + 1 )).0" ;;
patch) echo "$major.$minor.$(( patch + 1 ))" ;;
*) echo "bump.sh: unknown part: '$part'" >&2; return 2 ;;
esac
}
main() {
local part new
(( $# == 2 || $# == 3 )) || usage
part=$1
if [[ $2 == -f ]]; then
(( $# == 3 )) || usage
[[ -f $3 ]] || { echo "bump.sh: no such file: $3" >&2; exit 2; }
new=$(bump_version "$part" "$(< "$3")") || exit
printf '%s\n' "$new" > "$3"
echo "$3: $new"
else
(( $# == 2 )) || usage
bump_version "$part" "$2" || exit
fi
}
# Run main only when the file is executed. When a test sources it, only the
# functions are defined, and the caller's shell options stay unchanged.
if [[ ${BASH_SOURCE[0]} == "$0" ]]; then
set -euo pipefail
main "$@"
fi
bump_version checks the version with a regular expression (lesson 70): three numbers separated by dots, without leading zeros, as the semantic versioning rules require. The parentheses capture the three parts into BASH_REMATCH, and ${2#v} accepts an optional leading v, as in Git tags like v1.4.2. In -f mode, new=$(...) || exit stops before writing anything if the file's content is not a valid version, so an invalid file is never overwritten.
The last block makes the script testable at the function level. BASH_SOURCE[0] is the file being read and $0 is the program that was started; they are equal only when the file is executed directly. When a test loads the file with source, main does not run, and the test can call bump_version on its own. The set -euo pipefail line is inside that block for the same reason: a file that is sourced must not change the shell options of the shell that loads it.
The project layout puts tests in their own directory:
project/
├── bin/
│ └── bump.sh
└── test/
└── bump.bats
Anatomy of a Bats Test
A test file has the extension .bats and contains tests written with a special syntax:
@test "patch bump increases only the patch number" {
run "$BUMP" patch 1.4.2
[ "$status" -eq 0 ]
[ "$output" = "1.4.3" ]
}
@test "description" { ... }defines a test. Before running the file, Bats converts each@testblock into an ordinary Bash function. The description appears in the report, so it should state the expected behavior as a sentence.- Every line of a test is a check. Bats runs test functions with
set -ebehavior: if any command in the test returns a non-zero status, the test stops and is reported as failed, together with the failing line. A test passes when it reaches its end. runexecutes a command and records its result instead of failing. Afterrun, three variables are available:$statusholds the exit status,$outputholds everything the command printed to standard output and standard error, with the final newline removed, and the array${lines[@]}holds the output split into lines.- The checks are ordinary
testcommands,[ ... ].[ "$status" -eq 0 ]fails if the status is not 0;[ "$output" = "1.4.3" ]compares strings exactly.
run matters because many tests are about failures. Without it, a command that exits with status 2 would end the test immediately, and the test could not check that the status was 2 or that the error message was right. With run, the failure is captured, and the following lines decide whether it was the expected failure.
Isolation
Bats runs each test in its own process. The whole .bats file is loaded again for every test, so variables, functions and cd commands from one test can never leak into another. Tests can therefore run in any order, and a single test can be run alone. Code at the top level of the file, outside any test, runs once for each test; it should only define things, never perform work that must happen exactly once.
Setup, Teardown and Temporary Files
Most tests in a file need the same preparation. Bats calls a function named setup before each test and a function named teardown after each test, even when the test failed, which makes teardown the right place for cleanup. setup_file and teardown_file run once per file, before the first and after the last test.
setup() {
BUMP="$BATS_TEST_DIRNAME/../bin/bump.sh"
}
BATS_TEST_DIRNAME is the directory containing the .bats file. Building paths from it, instead of using relative paths, makes the tests work no matter from which directory bats is started.
Tests that create files need a place to put them. Writing into the project directory or into a fixed path such as /tmp/test risks conflicts between tests and leftover files. Since version 1.4.0, Bats creates a fresh, empty directory for each test, available as $BATS_TEST_TMPDIR, and deletes it after the test:
@test "-f updates the version file in place" {
echo 1.9.0 > "$BATS_TEST_TMPDIR/VERSION"
run -0 "$BUMP" minor -f "$BATS_TEST_TMPDIR/VERSION"
[ "$output" = "$BATS_TEST_TMPDIR/VERSION: 1.10.0" ]
[ "$(cat "$BATS_TEST_TMPDIR/VERSION")" = "1.10.0" ]
}
The test prepares a version file, runs the script on it, and checks two things: what the script reported, and what the file contains afterwards. Checking the file is the essential part, because a script can print the right message and still write the wrong data.
Checking Exit Status and Error Output
Version 1.5.0 added two options to run that make tests shorter and more precise:
run -N commandexpects exit statusNand fails the test immediately if the status differs.run -0expects success,run -2a usage error. Bats prints a warning when these options are used without declaring the minimum version at the top of the file withbats_require_minimum_version 1.5.0.run --separate-stderr commandkeeps standard error apart from standard output:$outputand${lines[@]}contain only standard output, while$stderrand${stderr_lines[@]}contain standard error.
Separating the two streams lets a test check that a script behaves well in a pipeline: results go to standard output, and messages go to standard error, where they do not corrupt the results.
@test "missing arguments print the usage on stderr only" {
run --separate-stderr -2 "$BUMP" patch
[ -z "$output" ]
[ "${#stderr_lines[@]}" -eq 2 ]
[[ ${stderr_lines[0]} == Usage:* ]]
}
The test expects status 2, nothing at all on standard output, and exactly two lines on standard error, the first starting with Usage:. The [[ ... == pattern ]] form checks a pattern instead of an exact string, which keeps the test from breaking when the wording of the second half of the line changes. Tests that check whole messages exactly are precise but must be updated whenever a message is reworded; partial matches such as [[ $output == *"unknown part"* ]] are a common compromise.
One portability note: in Bash 3.2, the version macOS ships, a failing [[ ... ]] that is not the last command of a test does not stop the test, so the failure goes unnoticed. The Bats documentation recommends either [ ... ], or appending || false to [[ ... ]] checks when tests must also run with Bash 3.2.
Testing Functions Directly
Testing a script through its command line covers the behavior users see. Testing its functions individually is useful for logic with many cases, because the tests become faster and failures point to a smaller piece of code. Because bump.sh only runs main when executed, a test can load it and call a function:
@test "bump_version can be called directly after sourcing the script" {
source "$BUMP"
run -0 bump_version patch 0.0.9
[ "$output" = "0.0.10" ]
}
source defines the script's functions in the test's process, and run works with functions as well as with programs. Since every test runs in its own process, the loaded functions disappear after the test.
Skipping Tests
Some tests can only run in certain environments, for example when a tool is installed. skip ends a test without counting it as a failure and records the reason:
@test "the script passes ShellCheck" {
command -v shellcheck > /dev/null || skip "shellcheck is not installed"
run -0 shellcheck "$BUMP"
}
A skipped test is visible in the report, so a missing tool does not silently reduce the test coverage. Lesson 190 explains how to make ShellCheck a fixed part of the development workflow.
Common Pitfalls with run
- Pipes apply to
run, not to the command.run my_cmd | grep xpipes the output ofrun, which prints nothing, intogrep, and$statusdescribesmy_cmdalone. To test a pipeline, run it through Bash:run bash -c 'my_cmd | grep x'. runexecutes in a subshell. Variables set by the command insiderunare not visible to the test afterwards. To check a variable that a function sets, call the function directly instead of throughrun.$outputmixes both streams by default. A test that compares$outputwith an exact string fails as soon as a command prints a warning on standard error. Use--separate-stderrwhen that matters.- Checks after
runmust actually check. A test consisting ofrun some_commandalone passes no matter what the command did, becauserunitself always succeeds. Either add checks or userun -0.
Helper Libraries: bats-assert
The plain [ ... ] checks have one weakness: when they fail, Bats reports the failing line, but not the actual value that was compared. The companion libraries bats-support and bats-assert provide assertion functions that print both the expected and the actual value on failure. They are usually added as Git submodules and loaded at the top of the test file with load:
setup() {
load 'test_helper/bats-support/load'
load 'test_helper/bats-assert/load'
BUMP="$BATS_TEST_DIRNAME/../bin/bump.sh"
}
@test "minor bump resets the patch number" {
run "$BUMP" minor 1.4.2
assert_success
assert_output "1.5.0"
}
@test "an unknown part is rejected" {
run "$BUMP" build 1.2.3
assert_failure 2
assert_output --partial "unknown part"
}
assert_success and assert_failure 2 check the status, assert_output compares the output exactly or, with --partial, as a substring, and assert_line --index 0 "..." checks a single line. load resolves paths relative to the test file's directory and adds the .bash extension automatically. The rest of this lesson uses plain checks, which need no extra libraries.
A Complete Example: A Test Suite for bump.sh
The complete test file covers the three kinds of bumps, invalid input, the file mode, direct function calls and static analysis. It is organized into groups with comments, and every test description states one expected behavior:
#!/usr/bin/env bats
#
# Tests for bin/bump.sh. Run them from the project root with: bats test
bats_require_minimum_version 1.5.0
setup() {
BUMP="$BATS_TEST_DIRNAME/../bin/bump.sh"
}
# ---- the three kinds of bump
@test "patch bump increases only the patch number" {
run "$BUMP" patch 1.4.2
[ "$status" -eq 0 ]
[ "$output" = "1.4.3" ]
}
@test "minor bump resets the patch number" {
run "$BUMP" minor 1.4.2
[ "$status" -eq 0 ]
[ "$output" = "1.5.0" ]
}
@test "major bump resets minor and patch and drops a leading v" {
run -0 "$BUMP" major v1.4.2
[ "$output" = "2.0.0" ]
}
@test "parts are numbers, so 9 is followed by 10" {
run -0 "$BUMP" minor 2.9.9
[ "$output" = "2.10.0" ]
}
# ---- invalid input
@test "an incomplete version is rejected with status 2" {
run -2 "$BUMP" minor 1.4
[ "$output" = "bump.sh: invalid version: '1.4'" ]
}
@test "leading zeros are rejected" {
run -2 "$BUMP" patch 01.2.3
}
@test "an unknown part is rejected" {
run -2 "$BUMP" build 1.2.3
[[ $output == *"unknown part: 'build'"* ]]
}
@test "missing arguments print the usage on stderr only" {
run --separate-stderr -2 "$BUMP" patch
[ -z "$output" ]
[ "${#stderr_lines[@]}" -eq 2 ]
[[ ${stderr_lines[0]} == Usage:* ]]
}
# ---- version files
@test "-f updates the version file in place" {
echo 1.9.0 > "$BATS_TEST_TMPDIR/VERSION"
run -0 "$BUMP" minor -f "$BATS_TEST_TMPDIR/VERSION"
[ "$output" = "$BATS_TEST_TMPDIR/VERSION: 1.10.0" ]
[ "$(cat "$BATS_TEST_TMPDIR/VERSION")" = "1.10.0" ]
}
@test "-f leaves the file unchanged when its content is invalid" {
echo 'not-a-version' > "$BATS_TEST_TMPDIR/VERSION"
run -2 "$BUMP" patch -f "$BATS_TEST_TMPDIR/VERSION"
[ "$(cat "$BATS_TEST_TMPDIR/VERSION")" = "not-a-version" ]
}
@test "-f with a missing file fails with status 2" {
run -2 "$BUMP" patch -f "$BATS_TEST_TMPDIR/missing"
[[ $output == *"no such file"* ]]
}
# ---- functions, tested without running main
@test "bump_version can be called directly after sourcing the script" {
source "$BUMP"
run -0 bump_version patch 0.0.9
[ "$output" = "0.0.10" ]
}
# ---- static analysis
@test "the script passes ShellCheck" {
command -v shellcheck > /dev/null || skip "shellcheck is not installed"
run -0 shellcheck "$BUMP"
}
What the Tests Cover
The tests were chosen to cover the decisions the script makes, not only its happy path:
- Each branch of the
casestatement has a test, so every kind of bump is checked once. - Boundaries and traps.
2.9.9to2.10.0checks that parts are treated as numbers, not as text; a string-based implementation would produce wrong results or sort incorrectly.v1.4.2checks the optional prefix. - Every error path returns status 2 with a meaningful message: incomplete versions, leading zeros, unknown parts, missing arguments and missing files. Lesson 187 goes deeper into testing error paths and exit codes.
- Side effects. The file tests check the file content after the command, including the important guarantee that an invalid file is left unchanged.
Running the Tests
From the project root, bats test runs every .bats file in the test directory (add -r to include subdirectories). In a terminal, Bats prints one line per test with a check mark for passed tests and a summary at the end, such as 13 tests, 0 failures, 1 skipped. When the output does not go to a terminal, for example in CI, or when --tap is given, Bats writes the Test Anything Protocol (TAP), a simple text format that many CI systems and tools understand:
$ bats --tap test
1..13
ok 1 patch bump increases only the patch number
ok 2 minor bump resets the patch number
ok 3 major bump resets minor and patch and drops a leading v
ok 4 parts are numbers, so 9 is followed by 10
ok 5 an incomplete version is rejected with status 2
ok 6 leading zeros are rejected
ok 7 an unknown part is rejected
ok 8 missing arguments print the usage on stderr only
ok 9 -f updates the version file in place
ok 10 -f leaves the file unchanged when its content is invalid
ok 11 -f with a missing file fails with status 2
ok 12 bump_version can be called directly after sourcing the script
ok 13 the script passes ShellCheck # skip (shellcheck is not installed)
The first line, 1..13, announces the number of tests. Each following line reports one test as ok or not ok, and the skipped test carries its reason.
To see what a failure looks like, a bug was introduced into bump.sh: the minor branch was changed to keep the patch number instead of resetting it to 0, a plausible mistake when editing the case statement:
minor) echo "$major.$(( minor + 1 )).$patch" ;;
Two tests catch it, and each failure report names the test, the file, the line and the check that failed:
$ bats --tap test
1..13
ok 1 patch bump increases only the patch number
not ok 2 minor bump resets the patch number
# (in test file test/bump.bats, line 22)
# `[ "$output" = "1.5.0" ]' failed
ok 3 major bump resets minor and patch and drops a leading v
not ok 4 parts are numbers, so 9 is followed by 10
# (in test file test/bump.bats, line 32)
# `[ "$output" = "2.10.0" ]' failed
ok 5 an incomplete version is rejected with status 2
...
ok 13 the script passes ShellCheck # skip (shellcheck is not installed)
The test -f updates the version file in place did not catch the bug, because its starting version 1.9.0 already has patch number 0. That is a useful observation about test design: a test only detects the bugs its data can reveal. Using a starting version with a non-zero patch number, such as 1.9.3, would make that test sensitive to this bug as well.
A note on how these results were produced: Bats could not be installed in the environment where this lesson was prepared, because it had no network access. The script and every test body were executed with a small stand-in harness that implements the parts of Bats used here (@test, setup, run with -N and --separate-stderr, $BATS_TEST_DIRNAME, $BATS_TEST_TMPDIR and skip) and prints TAP in the same format. The pass and fail results above, including the line numbers of the failures, come from that run with Bash 5.2. With real Bats, the TAP lines have the same structure; the exact wording of diagnostic lines can differ slightly between Bats versions.
Other Useful Options
bats --filter 'version file' testruns only tests whose description matches a regular expression, which is handy while working on one feature.bats --print-output-on-failure testshows the captured$outputof a failed test, so you can see what the command actually printed.bats --formatter junit test > report.xmlproduces a JUnit XML report, the format most CI systems use to display test results.bats --jobs 4 testruns tests in parallel; it requires GNUparallelto be installed, and tests must not share files outside$BATS_TEST_TMPDIR.
Running Bats in CI
The tests only protect the script if they run on every change. A minimal GitHub Actions job installs Bats and runs the suite; the job fails, and the change is marked as failing, whenever a test fails:
name: tests
on: [push, pull_request]
jobs:
bats:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: sudo apt-get update && sudo apt-get install -y bats shellcheck
- run: bats --tap test
Installing ShellCheck in the same job means the skipped test runs in CI, even if some developers do not have ShellCheck on their own machines. Lesson 177 explains how such pipeline steps use exit codes, and the next lesson shows how to test scripts that call external commands, such as curl, git or systemctl, by replacing those commands with controllable fakes.