Table of Contents

BASH - ShellCheck

ShellCheck helps to identify a lot of potential issues in your shell scripts.

For example, here is one common mistake which ShellCheck picks up. Most times, the original code will work. However if we feed $dir with value like “Denny Documents”, it hurts. Sometime the bad code may incur very severe damage!

# Before:

rm -rf $dir
 
# After:
<code bash>
rm -rf "$dir"

More Bad Code Examples

Common beginner's mistakes

ShellCheck recognizes many common beginner's syntax errors.

var = 42                              # Spaces around = in assignments.
$foo=42                               # $ in assignments.
for $var in *; do ...                 # $ in for loop variables.
var$n="Hello"                         # Wrong indirect assignment.
echo ${var$n}                         # Wrong indirect reference.
var=(1, 2, 3)                         # Comma separated arrays.

Style

ShellCheck can make recommendations to improve style:

[[ -z $(find /tmp | grep msg) ]]      # Use grep -q instead.
a >> log; b >> log; c >> log;         # Use a redirection block instead.
cat file | grep foo                   # Useless use of cat.

ShellCheck is very easy to install and use. It is built and packaged using Cabal. We can install by apt-get/yum. Or use cabal-install directly like below.

# Install ShellCheck
sudo apt-get install -y cabal-install
sudo cabal update
sudo cabal install shellcheck
ln -s /root/.cabal/bin/shellcheck /usr/sbin/shellcheck
 
# Example: Run check for Shell scripts
sudo shellcheck my_script.sh

By default, ShellCheck enforces hundreds of rules. Each rule has a dedicated wiki page, which explains the purpose and improvement suggestion clearly. For example, wiki for Rule SC1000: https://github…shellcheck/wiki/SC1000. I’m sure you can easily guess the wiki link of other rules.

Skip some ShellCheck rules, which don’t fit your projects. For your reference, here are rules I used to skip.

# Run test excluding certain rules
EXCLUDE_CODE_LIST="SC1090,SC1091,SC2154,SC2001,SC2002"
sudo shellcheck -e $EXCLUDE_CODE_LIST $file
 
# Run test against all scripts under a folder
EXCLUDE_CODE_LIST="SC1090,SC1091,SC2154,SC2001,SC2002"
find . -name "*.sh" | xargs sudo \
    shellcheck -e $EXCLUDE_CODE_LIST $file

It is recommended to enforce a daily Shell Code Check!