recent posts

Adding Static Analysis And Linting For Bash Scripts


For a long time, I wondered if there was a tool for keeping coding styles and best practices when coding in Bash. After a brief search, I finally found two tools that would help keep our bash scripts in check. This is especially important when working in teams that code heavily in bash, and is super helpful if integrated into a CI/CD pipeline.

Static Analysis

For Static Analysis, I found that ShellCheck did everything I needed it to do. It's an incredibly easy to setup tool that took only a few minutes to install. From the site, ShellCheck aims to do the following:
  • To point out and clarify typical beginner's syntax issues that cause a shell to give cryptic error messages.
  • To point out and clarify typical intermediate level semantic problems that cause a shell to behave strangely and counter-intuitively.
  • To point out subtle caveats, corner cases and pitfalls that may cause an advanced user's otherwise working script to fail under future circumstances.

Linting

For Linting, I wanted something that would enforce styles like making sure things were tabbed consistently, if/else statements were written in a consistent format. I found bashate which helped to enforce standards in Bash like PEP8 would for python. Installation was also super simple, all that was required was a quick `pip install bashate` or `pipenv install bashate` for my local command line. The installation README displays all of the rules it enforces, but here I would like to list a few that I liked.
  • E001: check that lines do not end with trailing whitespace
  • E002: ensure that indents are only spaces, and not hard tabs
  • E003: ensure all indents are a multiple of 4 spaces
  • E004: file did not end with a newline
  • E005: file does not begin with #! or have a .sh prefix

Tool Integration 

Integrating the tools is relatively simple and the tool READMEs provide guides on how to do so. Overall, you need to run the command line version of the tool and the script that you want to analyze. `shellcheck example.sh`, or ideally you'd want to add a script that traverses the folder structure, and retrieves all shell scripts to be analyzed. From there, you might want to also handle exit codes if you want your pipeline to fail when errors or warnings are found.
Adding Static Analysis And Linting For Bash Scripts Adding Static Analysis And Linting For Bash Scripts Reviewed by JJ The Engineer on 7:23 PM Rating: 5

No comments:

Powered by Blogger.