You are a budding programmer and you just wrote a simple shell script. You wanted to check if there are any bugs in it, but you don’t know how? No worries! Now, you can easily find bugs in your shell scripts using ShellCheck. It is a static analysis tool for shell scripts. ShellCheck will analyze the shell script and will display if there are any errors in your shell scripts instantly. It is written in Haskell language and freely distributed under GPLv3.
ShellCheck will analyze the script and do the following:
- Check for incorrect quoting,
- Check for incorrect test statements,
- Recognize incorrect commands,
- Recognize syntax errors,
- Suggest you to improve script's style,
- Recognize typos,
- Improve the robustness of your script,
- And check few other issues.
You don't need any expert's help to rectify bugs in your scripts. Just open ShellCheck, paste your script and boom! You can use ShellCheck either online or offline. In this brief tutorial, I will show you both!
ShellCheck on Web
You can check the scripts on online at any by visiting the ShellCheck website.
Open up your web browser and go to the following link.
Paste your shell script in it for instant feedback.
Note: I didn't write the script used in this example. I just found it online to test ShellCheck.
Alternatively, you can install it on your Linux box and test your script at anytime offline.
Install ShellCheck On Linux
ShellCheck is packaged for most Linux operating systems. You can easily install it using your distribution's package manager as shown below.
On Arch Linux and its derivatives:
$ sudo pacman -S shellcheck
On Debian, Ubuntu, Linux Mint, run the following command to install it:
$ sudo apt-get install shellcheck
On RHEL, CentOS enable EPEL repository:
$ sudo yum -y install epel-release
And install shellcheck:
$ sudo yum install ShellCheck
On Fedora systems:
$ sudo dnf install ShellCheck
On openSUSE (Tumbleweed edition), run the following command:
$ sudo zypper in ShellCheck
For other distributions, check the official installation page.
Find Bugs In Your Shell Scripts Using ShellCheck On Linux
Once installed, open Terminal and run the following command to test your scripts.
$ shellcheck myscript.sh
In myscript.sh line 1: # This script displays the date, time, username and ^-- SC2148: Tips depend on target shell and yours is unknown. Add a shebang. In myscript.sh line 6: echo "Your username is: `whoami` \\n" ^-- SC2006: Use $(..) instead of legacy `..`. ^-- SC2028: echo won't expand escape sequences. Consider printf.
As you see in the above output, ShellCheck indicates the suggestions at line 1 and line 6. Please be mindful that ShellCheck won't fix the errors in the scripts automatically. Instead, it will give warnings and suggestions for your shell scripts. This utility could be useful for anyone who wants to learn Shell scripting. Just write a script, copy/paste the code in ShellCheck and find the mistakes immediately.