Skip to content
$ lynuxpro
← Bash Scripting

LESSON 17 OF 17 · EXPERT · 22 MIN

Large script projects and testing with Bats

HOW IT WORKSStructure and test a large Bash project

sourcesourcebin/opsthin entrypointlib/*.shsourced functionsconfig.envsettingstest/*.batsBats testsshellchecklintCI pipelineon every push
1/4

Keep the entrypoint small. Put logic in library files of functions that it sources.

source "$(dirname "$0")/../lib/log.sh"

Small scripts live happily in one file. But platform teams often end up with Bash tooling that grows to thousands of lines: deploy helpers, cluster bootstrap scripts, release tooling. At that size the same rules apply as for any software: structure it into modules, keep configuration separate, test it automatically and run checks in CI. This lesson shows a project layout that scales, how to write unit tests with Bats, and how to wire everything into a pipeline.

In simple words

  • Project layout: splitting a big script into an entry point and small library files that are easy to read and test.
  • Bats: a testing framework for Bash. You write small tests that run your functions and check the results.
  • Mocking: replacing a real command with a fake one during tests, so tests are fast and safe.

When Bash is (and is not) the right tool

Bash is excellent at gluing commands together: calling kubectl, aws, git, tar and curl, moving files, checking exit codes. It is a poor fit when you need complex data structures, heavy JSON or YAML manipulation, maths, or long-lived services. A useful rule of thumb from experienced teams:

  • Under ~200 lines and mostly running other commands: Bash is great.
  • Lots of parsing, nested data or business logic: consider Python or Go.
  • In between: Bash, but structured and tested as described here.

A project layout that scales

ops-tools/├── bin/│   └── ops                  # thin entrypoint: parse options, call functions├── lib/│   ├── log.sh               # log, die, colours│   ├── config.sh            # load and validate settings│   ├── k8s.sh               # kubectl helpers│   └── util.sh              # small pure functions (easy to test)├── config/│   ├── defaults.env│   └── prod.env├── test/│   ├── util.bats│   └── config.bats├── Makefile                 # make lint, make test└── .gitlab-ci.yml           # runs lint and tests on every push
OUTPUTterminalutf-8 · 16L

The principles:

  • Thin entrypoint. bin/ops only parses options and calls functions. It contains almost no logic.
  • Libraries of functions. Each lib/*.sh file only defines functions and constants; it does nothing when sourced. That makes it safe to load in tests.
  • Pure functions where possible. A function that takes input as arguments and prints output, without touching the network or files, is trivial to test.
  • Configuration outside the code. Environment files per environment, loaded and validated in one place.

The entrypoint

#!/usr/bin/env bashset -euo pipefail # Find our own folder, even when called through a symlinkROOT=$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/.." && pwd)# shellcheck source=../lib/log.shsource "$ROOT/lib/log.sh"source "$ROOT/lib/util.sh"source "$ROOT/lib/config.sh" usage() { echo "usage: ops [-e ENV] COMMAND (deploy|status|rollback)"; } main() {  local env=staging opt  while getopts ":e:h" opt; do    case $opt in      e) env=$OPTARG ;;      h) usage; exit 0 ;;      *) usage >&2; exit 2 ;;    esac  done  shift $((OPTIND - 1))  load_config "$ROOT/config" "$env"   case ${1:-} in    deploy)   cmd_deploy "${@:2}" ;;    status)   cmd_status ;;    rollback) cmd_rollback ;;    *)        usage >&2; exit 2 ;;  esac} # Run main only when executed, not when sourced (so tests can source this file too)if [[ ${BASH_SOURCE[0]} == "$0" ]]; then  main "$@"fi
SHELLbashutf-8 · 36L
  • BASH_SOURCE[0] is the path of the current file, which works even when the file is sourced. $0 is the program that is running. When they are equal, the file was executed directly.
  • The # shellcheck source= comment tells ShellCheck where to find sourced files so it can check them too.

A small library

Build a library in the practice terminal. These are pure functions: input in, output out.

mkdir -p ops-tools/lib ops-tools/testprintf '# util.sh - small pure helpers\n\nslugify() {\n  local s=${1,,}\n  s=${s// /-}\n  printf "%%s\\n" "$s"\n}\n\nis_semver() {\n  [[ $1 =~ ^[0-9]+\\.[0-9]+\\.[0-9]+$ ]]\n}\n\nbump_patch() {\n  local major minor patch\n  IFS=. read -r major minor patch <<< "$1"\n  printf "%%s.%%s.%%s\\n" "$major" "$minor" "$((patch + 1))"\n}\n' > ops-tools/lib/util.shcat ops-tools/lib/util.shsource ops-tools/lib/util.shslugify "Checkout Service"is_semver 2.4.1 && echo "valid"is_semver v2 || echo "invalid"bump_patch 2.4.9
SHELLbashutf-8 · 8L
# util.sh - small pure helpersslugify() {  local s=${1,,}  s=${s// /-}  printf "%s\n" "$s"}is_semver() {  [[ $1 =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]}bump_patch() {  local major minor patch  IFS=. read -r major minor patch <<< "$1"  printf "%s.%s.%s\n" "$major" "$minor" "$((patch + 1))"}checkout-servicevalidinvalid2.4.10
OUTPUTterminalutf-8 · 21L

Testing with Bats

Bats (Bash Automated Testing System) is the standard test framework for Bash. A test file contains @test blocks; each block is a test that passes if every command in it succeeds.

#!/usr/bin/env bats setup() {  # runs before every test  source "$BATS_TEST_DIRNAME/../lib/util.sh"} @test "slugify lowercases and replaces spaces" {  run slugify "Checkout Service"  [ "$status" -eq 0 ]  [ "$output" = "checkout-service" ]} @test "is_semver accepts 2.4.1" {  run is_semver 2.4.1  [ "$status" -eq 0 ]} @test "is_semver rejects v2" {  run is_semver v2  [ "$status" -ne 0 ]} @test "bump_patch increments past 9" {  run bump_patch 2.4.9  [ "$output" = "2.4.10" ]}
SHELLbashutf-8 · 27L

The key pieces:

  • run command args executes the command and captures its exit code in $status, its combined output in $output, and its output lines in the ${lines[@]} array. run itself always succeeds, so a failing command does not stop the test; your assertions decide.
  • Assertions are ordinary test commands: [ "$status" -eq 0 ], [ "$output" = "…" ], [[ $output == *error* ]], [ "${lines[0]}" = "…" ]. The first failing one fails the test.
  • setup and teardown run before and after every test. Use them to source libraries and create or delete temporary files ($BATS_TEST_TMPDIR is a fresh folder per test).
  • $BATS_TEST_DIRNAME is the folder of the test file, so paths work no matter where you run bats from.

Write that test file and run it:

printf 'setup() {\n  source "$BATS_TEST_DIRNAME/../lib/util.sh"\n}\n\n@test "slugify lowercases and replaces spaces" {\n  run slugify "Checkout Service"\n  [ "$status" -eq 0 ]\n  [ "$output" = "checkout-service" ]\n}\n\n@test "is_semver accepts 2.4.1" {\n  run is_semver 2.4.1\n  [ "$status" -eq 0 ]\n}\n\n@test "is_semver rejects v2" {\n  run is_semver v2\n  [ "$status" -ne 0 ]\n}\n\n@test "bump_patch increments past 9" {\n  run bump_patch 2.4.9\n  [ "$output" = "2.4.10" ]\n}\n' > ops-tools/test/util.batsbats ops-tools/test/util.bats
SHELLbashutf-8 · 2L
 ✓ slugify lowercases and replaces spaces ✓ is_semver accepts 2.4.1 ✓ is_semver rejects v2 ✓ bump_patch increments past 94 tests, 0 failures
OUTPUTterminalutf-8 · 6L

A failing test

Tests are only useful if they catch mistakes. Break bump_patch on purpose (it now adds 2) and run the tests again:

sed -i 's/patch + 1/patch + 2/' ops-tools/lib/util.shbats ops-tools/test/util.batsecho "exit code: $?"
SHELLbashutf-8 · 3L
 ✓ slugify lowercases and replaces spaces ✓ is_semver accepts 2.4.1 ✓ is_semver rejects v2 ✗ bump_patch increments past 9   (in test file ops-tools/test/util.bats, line 21)4 tests, 1 failureexit code: 1
OUTPUTterminalutf-8 · 8L

Bats exits non-zero when any test fails, so a CI job fails too. Fix the bug and the suite goes green again:

sed -i 's/patch + 2/patch + 1/' ops-tools/lib/util.shbats ops-tools/test/
SHELLbashutf-8 · 2L

Testing code that calls other programs

Functions that run kubectl, curl or aws are harder to test: you do not want tests to touch a real cluster. The standard trick is to stub the command with a function or a fake script earlier in PATH:

setup() {  source "$BATS_TEST_DIRNAME/../lib/k8s.sh"  # fake kubectl: record the arguments, print canned output  kubectl() { echo "kubectl $*" >> "$BATS_TEST_TMPDIR/calls"; echo "deployment.apps/checkout scaled"; }  export -f kubectl} @test "scale_app calls kubectl with the right namespace" {  run scale_app checkout 4 prod  [ "$status" -eq 0 ]  grep -q "kubectl scale deployment/checkout --replicas=4 -n prod" "$BATS_TEST_TMPDIR/calls"}
SHELLbashutf-8 · 12L

The test checks what your code asked kubectl to do, which is exactly the logic you wrote. Helper libraries like bats-assert (assert_success, assert_output --partial) and bats-mock make this more readable as suites grow.

Linting and testing in CI

Wire both checks into a Makefile so everyone runs the same commands:

.PHONY: lint testlint:	shellcheck bin/* lib/*.shtest:	bats test/
OUTPUTterminalutf-8 · 5L

And run them in your pipeline on every push. A GitLab CI example:

stages: [check]lint:  stage: check  image: koalaman/shellcheck-alpine:stable  script:    - shellcheck bin/* lib/*.shtest:  stage: check  image: bats/bats:latest  script:    - bats --formatter junit test/ > report.xml  artifacts:    reports:      junit: report.xml
OUTPUTterminalutf-8 · 16L

The junit formatter lets GitLab show test results in merge requests. Now no broken or unchecked change to your tooling can be merged.

Other habits of large Bash projects

  • Version your tools and print it: ops --version. Tag releases in git.
  • Namespace function names (k8s_scale, log_info) so libraries do not collide.
  • Keep secrets out of scripts and out of traces: read them from the environment or a secrets manager, and never set -x around them.
  • Document every command in usage and keep a short README with examples.
  • Format consistently with shfmt -i 2 -w ., so diffs show real changes, not whitespace.
  • Prefer readability over clever one-liners. The next person debugging this at 3 a.m. may be you.

Real-world scenario: tests that saved a release

A team's release tool had a bump_version function that read the last git tag and incremented it. Someone "simplified" it to compare versions as strings, and 2.4.9 became 2.4.10… but sort then placed 2.4.10 before 2.4.9, so the next release reused an old version number and overwrote an artifact in the registry. After the incident they added a Bats test for exactly that case, plus ten more edge cases (v prefixes, -rc suffixes, missing tags). Two months later, a refactor broke the same logic again. This time the merge request pipeline failed on bump_patch increments past 9, and the bug never reached a release.

Common mistakes

  • Libraries that do work when sourced (running commands at the top level), which makes them impossible to test.
  • Testing only the happy path: add tests for empty input, spaces, missing files and failing commands.
  • Tests that call real systems: stub external commands instead.
  • Not using run: a failing command without run stops the test before you can check its output.
  • Skipping CI: tests that only run on one laptop are forgotten within a month.
  • Growing Bash past its strengths instead of moving complex logic to Python or Go.

Practice

  1. Add a function join_by SEP ITEMS… to util.sh that prints the items joined by the separator, and write two Bats tests for it.
  2. Add a test that checks slugify handles an input with several spaces.
  3. Break one function on purpose, watch the tests fail, then fix it.
  4. Write ops-tools/bin/ops with the "run main only when executed" guard, and source it in a test without running main.
  5. Write the Makefile with lint and test targets.

Cheat sheet

bin/  lib/  config/  test/          project layoutsource "$ROOT/lib/x.sh"             load a library[[ ${BASH_SOURCE[0]} == "$0" ]] && main "$@"   run only when executed# shellcheck source=lib/x.sh        help ShellCheck follow sources@test "name" { … }                  a Bats testsetup() / teardown()                before / after each testrun cmd args                        capture $status, $output, ${lines[@]}[ "$status" -eq 0 ]                 assert success[ "$output" = "x" ]                 assert outputbats test/                          run all testsbats --formatter junit test/        CI reportcmd() { …; }; export -f cmd         stub an external commandshellcheck bin/* lib/*.sh           lint everythingshfmt -i 2 -w .                     consistent formatting
OUTPUTterminalutf-8 · 14L

Key takeaways

  • Structure large Bash projects as a thin entrypoint plus libraries of functions, with configuration kept separately.
  • Libraries should only define functions, so tests can source them safely.
  • Bats tests use run to capture $status and $output, then plain test commands as assertions.
  • Stub external commands so tests check your logic without touching real systems.
  • Run ShellCheck and Bats in CI on every change, and move to Python or Go when Bash stops being the simplest tool.