Shellcheck
22 January 2019Photo: Unsplash
I am going to take a noteworthy detour from i3wm this week. As part of updating my dotfiles repository, I wanted to highlight a very useful tool when developing scripts - Shellcheck.
I came across this utility while reviewing some scripts in Jess Frazelle’s repositories. Shellcheck is a static code analysis tool for bash and sh scripts. Developed by Vidar Holen, the tool can be used in a variety of ways including from the shell and via a web tool.
Side note - Jess’s repositories are an excellent learning source and her twitter brightens most days!
The aim of Shellcheck is to:
- Find and clarify typical beginner syntax. It will also make it easier to understand cryptic error messages that the shell can print.
- Make it easier to resolve statements that cause the shell to behave in a less than intuitive way.
- Point out more advanced issues that will cause the user’s script fail in particular corner cases.
The easiest way to try the application out is to head to shellcheck.net and paste a script snippet into the editor.
As you can see from the image above, as you enter your code the issues Shellcheck finds are output below. The issues that it lists are all defined by an Id and provide a small amount of data. It also tries to align the issues to the statement or variables that it refers to. This makes it easier to see which piece of code is the cause of the issue.
The next way to work with Shellcheck is via the command line by installing it locally. I installed Shellcheck (on any Arch-based system) with
Once installed you can get the same output as shown in the web interface by calling shellcheck with the script you want to check. Such as:
This will result in the output of Shellcheck being written to your terminal.
The last way in which you can use Shellcheck is to integrate it with your editor but I have yet to do this. I will look at this when I overhaul my Vim configuration. Full details are given on the Shellcheck site.
The best feature of Shellcheck is not it’s useful linting of your scripts but the excellent Wiki on its Github page. Thanks to the Id’s that Shellcheck assigns to each error you can easily look up the details on the wiki. Each error has clear details on what it has found and why it is a problem. It also provides an example of the solution it proposes. I have (re)learnt many core idea’s when scripting while using Shellcheck.
Needless to say, I now have a script in my dotfiles that runs Shellcheck against each script file.
This kind of utility is so powerful. They improve consistancy, remove basic issues and enforce a standard style. I highly recommend adding Shellcheck to your utility collection.
If you have tips or advice on Shellcheck then contact me via twitter or email.