Bash Linting. Checking your scripts are nice and lint free
Continiuing on from my previous post on testing shell scripts with bats I have been looking for a linting solution for shell scripts. And I think I have found a nice one in shellcheck. Which is aviailble as both a website and a packge on debian.
It's really simple to run just give it your shell script as an argument and you get a nice set of comments on the style of your code. Here is the result of testing their test script.
#!/usr/bin/env bash ## Example of a broken script. Hit the Down Arrow button to ShellCheck it! for f in $(ls *.m3u) do grep -qi hq.*mp3 $f \ && echo 'Playlist $f contains a HQ file in mp3 format' done
Then run shellcheck foo.sh
In foo.sh line 3: for f in $(ls *.m3u) ^-- SC2045: Iterating over ls output is fragile. Use globs. ^-- SC2035: Use ./*.m3u so names with dashes won't become options. In foo.sh line 5: grep -qi hq.*mp3 $f \ ^-- SC2062: Quote the grep pattern so the shell won't interpret it. ^-- SC2086: Double quote to prevent globbing and word splitting. In foo.sh line 6: && echo 'Playlist $f contains a HQ file in mp3 format' ^-- SC2016: Expressions don't expand in single quotes, use double quotes for that.
I have a simple makefile now that's just there mostly as a reminder of the testing that is aviailble for that script.
bats: *.bats bats *.bats lint: your_script your_nextscript shellcheck your_script shellcheck your_nextscript
Next up is intergration with vim. I use the really nice syntastic vim plugin. Syntastic does automatic style checking on files as you save them and shows a set of errors. Installing it is simple. Install shellcheck, I use apt-get install shellcheck
on Debian but you can use your favorite way on your OS. Then install the vim syntastic, again I use Vundle so adding Bundle scrooloose/syntastic
to my .vimrc and then running BundleInstall
in vim did the trick for me. Now when I write a shell script to disk vim will comment on my style.
Comments
Comments powered by Disqus