Debugging Bash Scripts - Part 4 - ShellCheck

Here is the list of all the Bash debugging posts:

This one is pretty simple. Either install ShellCheck with your package manager or use the website tool to check your scripts.

It will check for any buggy code and also offer syntax advice like quoting variables.

The following script won’t run as it has a syntax error:


for i in {1..10}: do
    mkdir $i

However, the error on execution isn’t too easy to understand:

$ ./
./ line 4: syntax error near unexpected token `mkdir'
./ line 4: `    mkdir $i'

ShellCheck will give you much better advice on what the problems are and how to fix them, e.g.:

$ shellcheck

In line 3:
for i in {1..10}: do
                  ^-- SC1063 (error): You need a line feed or semicolon before the 'do'.

In line 4:
    mkdir $i
          ^-- SC2086 (info): Double quote to prevent globbing and word splitting.

Did you mean:
    mkdir "$i"

For more information: -- You need a line feed or semicolon... -- Double quote to prevent globbing ...

As ShellCheck noted, I put a full-colon: where I should have put a semi-colon ;. Also, you should always quote variables.

It’s worth adding ShellCheck into your deployment pipeline if you are using Bash scripts to enforce safe scripting. ShellCheck will give an exit code 0 only if there are no problems found (which are also configurable) making it easy to automate this process.