Introduction on how to use shellcheck and bashate with Travis-CI

Introduction

Some time ago i've written about test-driven development, or TDD, for shell scripts using shunit2 and Travis-CI. This time i want to show you how you can further enhance your shell script testing capabilities with two useful tools for static analysis and style checking.

TL;DR

For anyone who has no time to read the full post, check out the Github Repo i've setup which shows you how to achieve the shellcheck and bashate integration with Travis-CI.

Getting shellcheck and bashate

I assume that you're developing with macOS, so getting shellcheck and bashate is pretty easy.

You can get both using Homebrew and pip. For pip you first need to install python with Homebrew.

brew install shellcheck

and

brew install python

followed by a

pip install bashate

Testing a script with both tools

This is super simple. While you've installed both via Homebrew, they're now accessible in your $PATH variable and you can easily run them on your shell script you want to test with:

shellcheck your-script.sh

and

bashate your-script.sh

Both tools will output parts of your script with the errors or warnings they found shortly explaining the problems. Shellcheck also has so called directive id's and a wiki where you can learn more about the errors found and how you can fix them.

Integrating both tools with Travis-CI

That's also quite straight forward. Easily copy and paste the following .travis.yml into your git's root folder and upload it to Github for example.

sudo: required
dist: trusty
language: bash

before_install:
    - sudo apt-add-repository "deb http://archive.ubuntu.com/ubuntu trusty-backports main restricted universe multiverse"
    - sudo apt-get -qq update
    - sudo apt-get -t trusty-backports install shellcheck
    - sudo pip install bashate

script:
- shellcheck your-script.sh
- bashate your-script.sh

Since we need to add a the trusty-backports repository and Ubuntu Trusty in Travis-CI for shellcheck, we need to add the sudo: required parameter and dist: trusty as well as the full before_install part. With this we add the trusty-backports repository so we can get shellcheck from it. Bashate is simply installed using pip, whereas python and pip are pre-installed on Ubuntu.

In the script: section we call both tools with the path from the repository root to the shell scripts we want to test. shellcheck will exit 1 when it finds errors and bashate will do the same except for warnings like you can see in my example repository.

Are we done here?

Yes! You have successfully setup basic static analysis and style checking for your bash scripts using shellcheck and bashate with Travis-CI. Your build status should look like this now:

Build Status

Congratulations and happy testing!