How to Write Unit Tests for Bash Scripts (The Simple Way)

How to Write Unit Tests for Bash Scripts (The Simple Way)

Written by Bobby Iliev on Apr 11th, 2025 Views Report Post

Introduction

If you enjoy writing Bash scripts to automate tasks, then you might ask yourself: "Can I write tests for my Bash scripts?".

The answer is: Yes, you can! And it's not hard at all.


🛠️ What You Need

We will use a tool called bats. It lets you write tests for Bash scripts in a clean and simple way.

To install it:

brew install bats-core  # On macOS
# OR
sudo apt install bats  # On Ubuntu/Debian

🧪 A Simple Bash Script Example

Let’s say you have this function in script.sh:

#!/bin/bash

say_hello() {
  echo "Hello, $1!"
}

✅ How to Test It

Create a file called test_script.bats:

#!/usr/bin/env bats

load './script.sh'

@test "say_hello prints the correct message" {
  run say_hello "Bobby"
  [ "$status" -eq 0 ]
  [ "$output" = "Hello, Bobby!" ]
}

Then run the tests with:

bats test_script.bats

🤖 Run Tests with GitHub Actions

You can also run the tests automatically using GitHub Actions.

Create a .github/workflows/test.yml file:

name: Bash Script Tests

on:
  pull_request:
    branches: [ main ]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Install BATS
        run: sudo apt-get update && sudo apt-get install -y bats
      - name: Run tests
        run: bats test_script.bats

Every time you push changes or open a pull request, your tests will run automatically. This helps you catch problems early.


📘 Learn More About Bash

If you are just starting with Bash scripting, I wrote a free and open-source book that explains the basics step by step:

Introduction to Bash Scripting

It covers loops, variables, functions, and more. Perfect for beginners.


If you want to try this on a cloud server, I use and recommend DigitalOcean. You'll get $200 in free credits for 60 days. Great for running your projects, testing scripts, or learning Linux.

If you have questions or want to chat more about Bash or DevOps, feel free to reach out on Twitter/X: @bobbyiliev_

Thanks for reading and happy scripting!

– Bobby

Comments (0)