ShellCheck: Code Check For Shell Scripts

Shell scripting is a must-have skill for DevOps. I used to be very very confident at Shell. But when I first tried ShellCheck, I realized that I’m just too proud and arrogant.
ShellCheck is a powerful code analysis tool for shell scripts. Like Pylint for Python or Rubocop for Ruby. Give it a try! You’ll get surprised.

ShellCheck Code Check For Shell Scripts



ShellCheck helps to identify a lot of potential issues in your shell scripts. For example, here is one common mistake which ShellCheck reminds me. Mostly original code will work. However if we feed $dir with value like “My Documents”, it hurts. Sometime the bad code may incur very severe damage!

# Before:
rm -rf $dir
# After:
rm -rf "$dir"

Note: If you’re using Ruby heavily, check about this: Common Rubocop Errors.

More Bad Code Examples:

Shell bad code
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. In mac OS, try “brew install shellcheck”.

# 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

Enforce Daily Shell Code Check by Jenkins. Enforce code quality check in your daily CI definitely helps.

github_BashCodeQualityCheck.png

More Reading:

linkedin
github
slack

PRs Welcome

Blog URL: https://www.dennyzhang.com/shellcheck


3 Responses to ShellCheck: Code Check For Shell Scripts

  1. This is a great idea. Is it specifically for bash or will it work on Korn shell scripts too but maybe with some limitations?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.