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:

#!/bin/bash

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

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

$ ./bad-script.sh
./bad-script.sh: line 4: syntax error near unexpected token `mkdir'
./bad-script.sh: line 4: `    mkdir $i'

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

$ shellcheck bad-script.sh

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


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

Did you mean:
    mkdir "$i"

For more information:
  https://www.shellcheck.net/wiki/SC1063 -- You need a line feed or semicolon...
  https://www.shellcheck.net/wiki/SC2086 -- 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.