Linux: Static analyze shell script with ShellCheck

This article will describe usage of ShellCheck.

1 Install ShellCheck

Install shellcheck package in case of Ubuntu.

$ sudo apt install -y shellcheck

Install ShellCheck package from EPEL in case of CentOS.

$ sudo yum install -y epel-release
$ sudo yum install -y ShellCheck

2 Static analyze with ShellCheck

Static analyze the following shell script with ShellCheck.

$ cat SC2068.sh
#!/bin/sh

for arg in $@; do
  echo arg = "${arg}"
done

ShellCheck reports error about no double quote around $@.

$ shellcheck SC2068.sh

In SC2068.sh line 3:
for arg in $@; do
           ^-- SC2068: Double quote array expansions, otherwise
they're like $* and break on spaces.

3 Supported shell

ShellCheck supports sh, bash and ksh. ShellCheck reports according to each shell's syntax.

ShellCheck detects shell with shebang. But if shell script does not have shebang like in case of bash completion, you can set shell with -s option.

$ shellcheck -s sh <script>

4 Supported output format

ShellCheck supports output format available in editors and Jenkins.

4.1 gcc

Usinig -f gcc option will output like GCC.

$ shellcheck -f gcc <script>

This is useful for code jumping on emacs. The following is running shellcheck command in "Compile command"

0001_shellcheck-gcc.png

4.2 checkstyle

Using -f checkstyle option will output checkstyle format. Jenkins's Checkstyle Plugin treats checkstyle format as test result.

If shellcheck command detects error including "note:", shellcheck command will return non-zero value. Because Jenkins's "Execute shell" in "Build" treats non-zero value of command as build error, shellcheck reports will be treated as build error and Checkstyle Plugin will not read it. So you need to force shellcheck's return value be zero.

shellcheck -f checkstyle <script> > checkstyle.xml || true

Setting this checkstyle.xml to "Publish Checkstyle analysis results" in "Post-build Actions" displays as below.

0002_shellcheck-checkstyle.png