Testing Bash Scripts with Bats

Bats testing workflow validating Bash deployment scripts, errors, and generated files in an isolated sandbox

What You’ll Learn

In this lesson, you will learn how to use Bats, the Bash Automated Testing System, to create repeatable tests for shell scripts. You will test both successful operations and expected failures in deployment and file-processing workflows.

  • Install and run Bats tests.
  • Use run, $status, and $output to inspect commands.
  • Create isolated temporary test directories.
  • Test success paths, error paths, and generated files.
Ad

The Concept

Bats is a testing framework designed for Bash scripts. A Bats test file normally uses the .bats extension and contains one or more @test blocks.

Instead of manually running a script and checking its output, a Bats test records the expected behavior. You can then run the same tests after changing the script, before deploying it, or in a continuous integration pipeline.

Install Bats using the package manager appropriate for your operating system. For example, Homebrew provides the bats-core package, and many Linux distributions provide a package named bats.

brew install bats-core
bats --version

After installation, run a test file with bats followed by its path:

bats test/deploy_files.bats

Bats provides useful variables and commands inside a test:

  • run command arguments executes a command without immediately ending the test when the command fails.
  • $status contains the command’s exit status.
  • $output contains the command’s standard output.
  • setup runs before each test.
  • teardown runs after each test.

This makes Bats useful for scripts that deploy files, create directories, transform input, or return different exit statuses for different failures. For larger deployment workflows, the tested commands may eventually be executed on managed servers; AWS Systems Manager Run Command is one example of a tool that can execute and monitor administrative shell commands remotely.

Basic Example

Suppose a deployment script copies regular files from a source directory into a release directory. The script should create the destination directory, report success, and return a useful error when the source directory does not exist.

Save the following as deploy_files.sh and make it executable with chmod +x deploy_files.sh:

#!/usr/bin/env bash

set -euo pipefail

if [[ "$#" -ne 2 ]]; then
    printf 'Usage: %s SOURCE_DIR DESTINATION_DIR\n' "$0" >&2
    exit 64
fi

source_dir=$1
destination_dir=$2

if [[ ! -d "$source_dir" ]]; then
    printf 'Source directory not found: %s\n' "$source_dir" >&2
    exit 2
fi

mkdir -p "$destination_dir"

while IFS= read -r -d '' file; do
    cp "$file" "$destination_dir/"
done < <(find "$source_dir" -maxdepth 1 -type f -print0)

printf 'Deployed files to %s\n' "$destination_dir"

Now create test/deploy_files.bats:

#!/usr/bin/env bats

PROJECT_ROOT="$(cd "$(dirname "$BATS_TEST_FILENAME")/.." && pwd)"

setup() {
    TEST_ROOT=$(mktemp -d)
    mkdir -p "$TEST_ROOT/source"
    printf 'release notes\n' > "$TEST_ROOT/source/notes.txt"
}

teardown() {
    rm -rf "$TEST_ROOT"
}

@test "deploys regular files into a new destination" {
    run "$PROJECT_ROOT/deploy_files.sh" \
        "$TEST_ROOT/source" \
        "$TEST_ROOT/release"

    [ "$status" -eq 0 ]
    [ "$output" = "Deployed files to $TEST_ROOT/release" ]
    [ -f "$TEST_ROOT/release/notes.txt" ]
    [ "$(cat "$TEST_ROOT/release/notes.txt")" = "release notes" ]
}

@test "fails when the source directory does not exist" {
    run "$PROJECT_ROOT/deploy_files.sh" \
        "$TEST_ROOT/missing" \
        "$TEST_ROOT/release"

    [ "$status" -eq 2 ]
    [ "$output" = "Source directory not found: $TEST_ROOT/missing" ]
}

Run the test from the project directory:

mkdir -p test
chmod +x deploy_files.sh
bats test/deploy_files.bats

Expected Output

✓ deploys regular files into a new destination
✓ fails when the source directory does not exist

2 tests, 0 failures

How the Code Works

A process flow showing each Bats test creating an isolated temporary workspace, running a Bash script with run, capturing status and output, and verifying expected messages, exit codes, and generated files before cleanup and test completion.
Bats makes Bash tests repeatable by isolating filesystem state, capturing command results, checking success and failure paths, and validating generated files before cleanup.

The test uses setup to create a fresh temporary directory before each test. mktemp -d creates a unique directory, which prevents one test from accidentally using files left by another test.

The teardown function removes that directory after the test. This cleanup is important because tests should not modify a developer’s real deployment directories or depend on the order in which tests run.

The run command lets the test inspect both successful and unsuccessful commands. Without run, a nonzero status could cause the test to stop before you can check whether that failure was expected.

The first test checks four behaviors:

  • The deployment script exits with status 0.
  • Its output names the destination directory.
  • The destination directory contains the copied file.
  • The copied file contains the expected content.

The second test verifies an intentional failure. Testing error paths is especially valuable for deployment scripts because a script that silently continues after a missing source directory can produce an incomplete release.

The deployment script uses find with -print0 and reads the results with read -d ''. This handles filenames containing spaces more safely than splitting a plain command substitution on whitespace. The script only searches the source directory’s top level, so nested directories are not copied.

Another Example

Bats is also useful for file-processing scripts. The following script reads one entry per line, removes duplicate entries, sorts the result, and writes it to a new file. For a broader Bash workflow involving sorting and deduplicating text, see Bash sort and uniq for file processing.

Save this as unique_entries.sh:

#!/usr/bin/env bash

set -euo pipefail

if [[ "$#" -ne 2 ]]; then
    printf 'Usage: %s INPUT_FILE OUTPUT_FILE\n' "$0" >&2
    exit 64
fi

input_file=$1
output_file=$2

if [[ ! -f "$input_file" ]]; then
    printf 'Input file not found: %s\n' "$input_file" >&2
    exit 2
fi

sort -u "$input_file" > "$output_file"
printf 'Wrote unique entries to %s\n' "$output_file"

A separate Bats file can test both the transformed content and the missing-input error:

#!/usr/bin/env bats

PROJECT_ROOT="$(cd "$(dirname "$BATS_TEST_FILENAME")/.." && pwd)"

setup() {
    TEST_ROOT=$(mktemp -d)
    printf 'warning\nerror\nwarning\ninfo\n' > "$TEST_ROOT/events.log"
}

teardown() {
    rm -rf "$TEST_ROOT"
}

@test "writes sorted unique entries" {
    run "$PROJECT_ROOT/unique_entries.sh" \
        "$TEST_ROOT/events.log" \
        "$TEST_ROOT/summary.log"

    [ "$status" -eq 0 ]
    [ "$output" = "Wrote unique entries to $TEST_ROOT/summary.log" ]
    [ "$(cat "$TEST_ROOT/summary.log")" = $'error\ninfo\nwarning' ]
}

@test "fails when the input file does not exist" {
    run "$PROJECT_ROOT/unique_entries.sh" \
        "$TEST_ROOT/missing.log" \
        "$TEST_ROOT/summary.log"

    [ "$status" -eq 2 ]
    [ "$output" = "Input file not found: $TEST_ROOT/missing.log" ]
}

The test checks the final file rather than only checking the command’s output. This is an important pattern for file-processing scripts: a success message does not prove that the generated file has the correct contents.

Common Mistakes

  • Checking only the exit status: A command can exit successfully while producing incorrect output. Check generated files or important output as well.
  • Using real project directories: Tests should use temporary directories so they cannot overwrite a developer’s files or depend on previous test runs.
  • Forgetting expected failures: Missing files, invalid arguments, and permission problems are normal scenarios worth testing. Use run and assert the expected nonzero status.
  • Assuming tests share state: Bats runs setup and teardown around each test. Create all required input data inside setup.
  • Testing only happy paths: Deployment and file-processing scripts often fail at their boundaries. Include empty directories, missing inputs, and unexpected directory structures where those cases matter.

Try It Yourself

Add a Bats test for unique_entries.sh that passes an empty input file. The script should exit with status 0, create the output file, and leave it empty.

Run the test suite after adding your test. A correct test should verify both the exit status and the existence or contents of the output file.

Challenge

Extend the deployment tests with two cases:

  • Verify that an empty source directory still succeeds and creates the destination directory.
  • Verify that a regular file inside a nested directory is not copied, because the deployment script is intended to process only files directly inside the source directory.

Use a fresh temporary directory for each test and check the relevant exit status and filesystem results.

Solution

Add these tests to test/deploy_files.bats:

@test "creates the destination for an empty source directory" {
    empty_source="$TEST_ROOT/empty-source"
    empty_release="$TEST_ROOT/empty-release"
    mkdir -p "$empty_source"

    run "$PROJECT_ROOT/deploy_files.sh" \
        "$empty_source" \
        "$empty_release"

    [ "$status" -eq 0 ]
    [ "$output" = "Deployed files to $empty_release" ]
    [ -d "$empty_release" ]
    [ -z "$(find "$empty_release" -mindepth 1 -print -quit)" ]
}

@test "does not copy files from nested directories" {
    nested_source="$TEST_ROOT/nested-source"
    nested_release="$TEST_ROOT/nested-release"
    mkdir -p "$nested_source/archive"
    printf 'old release\n' > "$nested_source/archive/old.txt"

    run "$PROJECT_ROOT/deploy_files.sh" \
        "$nested_source" \
        "$nested_release"

    [ "$status" -eq 0 ]
    [ -d "$nested_release" ]
    [ ! -e "$nested_release/old.txt" ]
    [ -z "$(find "$nested_release" -mindepth 1 -print -quit)" ]
}

The first test confirms that mkdir -p creates the destination even when find discovers no files. The second test documents the script’s top-level-only behavior and prevents a future change from accidentally copying nested archive files.

Key Takeaways

  • Bats turns Bash commands and exit statuses into repeatable automated tests.
  • Use run, $status, and $output to test both success and failure paths.
  • Use temporary directories and cleanup functions to isolate filesystem tests.
  • Test generated files and side effects, not just success messages.
  • Deployment and file-processing scripts benefit from explicit tests for missing inputs, empty inputs, and directory boundaries.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top
Ad
Ad
Ad