Shellcheck analyses scripts, and informs about errors and warnings, alike to what a compiler would do.
What Isshellcheck?
Introducing bugs into code is bound to happen when humans are developing code.
Even the best developers may once in a while miss a unforeseen complexity or caveat in their code.
In Bash, there is no real compiler as there is for example in C++.
There are however a set of tools which can help greatly when developing Bash scripts.
Once such a tool is shellcheck.
It is a bit like having a compiler for Bash.
< start
fif
How many bugs can you find?
(Tip: there are 8!).
If you haven’t heard of shebang yet, just checkout ourBash Automation and Scripting Basics Part 1article.
Our pun shebang line#!/bin/washshould be#!/bin/bash.
Shutterstock/MarcoVector
Let’s fix this.
We reran shellcheck and are now presented with the following:
Another single quote issue.
We already know how to fix these.
Let’s changeecho ‘sure!
< starttoecho ‘sure!’
< start(issue 5/8 fixed!)
What a careless mistake ;) Easily fixed (issue 6/8 fixed!).
Our script now looks like this:
if [ -d ./directory ]; then
echo ‘sure!’
< start
And another shellcheck run provides us with another helpful bit of information:
We have a missingfi!
Aha, yes,fifwill not do.
We changefiftofion the last line of the script (issue 7/8) fixed and run shellcheck once more!
Indeed our redirection was intended to be>instead of<.
Issue 8/8 - all issues - fixed!
This brings us to the final script
echo ‘sure!’
start
fi
Let’s see what shellcheck thinks of it now.
And the script runs perfectly, from the first execution.
Clicking on such a link will take you to theshellcheck GitHub project.
In a Rush?
You may even be able to use shellcheck in that coding challenge for your next live Bash coding interview!
In this article we explored various issues which could arise in scripts and howshellcheckhandles them.