What is ShellCheck, and how do you use it?

ShellCheck is a shell script linter. It is a tool that statically analyzes shell scripts for any shenanigans such as syntax errors, stylistic, and deprecated ways of writing shell scripts and suggests ways of improving the quality of the written code.

What makes ShellCheck special is that it is available everywhere for your convenience:

  • Online at www.shellcheck.net, where you can copy/paste your script to give it a quick static analysis
  • From within your favorite code source editor, for instance, VSCode with the extension vscode-shellcheck
  • From the terminal – after installing the shellcheck package, you can type shellcheck your-script.sh
  • ShellCheck can be incorporated into most Continuous Integration services, like Travis CI or Github Actions

Example

On a Debian machine, we install the tool using sudo apt-get install shellcheck Then, we create a file with the following buggy bash script:

#!/bin/bash
# Game for guessing a previously set number.
echo "Guess game"
echo "in 5 steps only."
echo ""
random_number=${shuf -i1-10 -n1}
declare -i guess_num
for i in {1..5}; do
read -r -p "What is your guessed number, please ? " guess_num
if [ "$guess_num" -eq "$random_number" ]; then
echo "Success !"
break
elif [ $i -q 5 ]; then
echo "End, sorry you failed it was $random_number"
break
else
echo "Failed for the $i !"
continue
fi
done

Now, from within the same directory, we will run ShellCheck on the guess_game.sh bash script. The result of this is:

Terminal 1
Terminal
Loading...

In the previous example, ShellCheck was run on a simple bash script. As you can see, it spots an error on line 9 of the file guess_game.sh and it displays a warning that shuf is referenced but not assigned under the identifier SC2154.

Further details related o this error can be found here.