Bash scripts deserve automated static analysis too

Albert Lombarte
Sep 7, 2018 · 2 min read

Although one can found bash scripts in millions of diverse projects and for all sorts of purposes, what is very difficult to find is a little bit of measures to ensure a minimum of quality. In under 2 minutes you can assure your scripts are safe with this simple recipe.

whatever…

Enters ShellCheck

From their man page:

ShellCheck is a static analysis and linting tool for sh/bash scripts. It’s mainly focused on handling typical beginner and intermediate level syntax errors and pitfalls where the shell just gives a cryptic error message or strange behavior, but it also reports on a few more advanced issues where corner cases can cause delayed failures.

TL;DR

  • Mac: brew install shellcheck
  • Linux: sudo apt-get install shellcheck

Once you have it installed you can test all the bash scripts in your project using a single command:

shellcheck **/*.sh

The output of the tool when there are errors

You might want to install an IDE or text editor integration to have automatic linting, there are multiple plugins for all sorts of systems. Check the Github for additional info.

Adding ShellCheck to CI

Now the final part is to automate this, so whenever you commit you can actually see the status of the project. Good news is that Travis-CI comes with shellcheck preinstalled so there is nothing you need to do. This is an example on how to integrate it:

.travis.yml content:

language: shell
sudo: false
script:
- bash -c 'shopt -s globstar; shellcheck **/*.sh'

If you don’t use Travis this can be added in other CI system, but you will probably need to install it manually using cabal. Final step, add your repository to travis and commit the file, you will have now the report on every commit!

An example of my dotfiles repo:

Enjoy!

Albert Lombarte

Written by

Delivering KrakenD, the fastest API Gateway. CEO of Brutale Engineering. Independent technology advisor in several companies.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade