shellcheck
ShellCheck reads your bash and tells you what is wrong before bash does. It catches the silent failures strict mode plus testing cannot.
ShellCheck in your workflow
EXAMPLE
# Install
# macOS: brew install shellcheck
# Ubuntu: apt install shellcheck
# Windows: scoop install shellcheck
# Lint a script
shellcheck deploy.sh
# Example issues it catches:
# - Unquoted variable expansion
# Wrong
echo $file
# ShellCheck warning SC2086: Double quote to prevent globbing.
# Right
echo "$file"
# - Using which instead of command -v
# Wrong
if which jq; then ...
# Warning SC2230: command -v is preferred for portability.
# Right
if command -v jq > /dev/null; then ...
# - cd without check
# Wrong
cd /opt/app
rm -rf build
# Warning SC2164: Use cd ... || exit
# Right
cd /opt/app || exit 1
rm -rf build
# - Reading from a pipe loses variables
# Wrong
cat list | while read x; do count=$((count+1)); done
echo $count # always 0
# Warning SC2031: Loop changes variable in a subshell.
# Right
while read -r x; do count=$((count+1)); done < list
echo $count
# - useless cat
# Wrong
cat file | grep foo
# Warning SC2002
# Right
grep foo file
# CI integration - GitHub Actions
name: shell
on: [pull_request]
jobs:
shellcheck:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: ludeeus/action-shellcheck@master
with:
ignore_paths: 'vendor third_party'
# Editor integration
# - VS Code: 'ShellCheck' extension from timonwong
# - Neovim: nvim-lint or null-ls
# - JetBrains: built-in Shell Script inspection uses ShellCheck
# Suppressing rules - rare, justify in comments
# shellcheck disable=SC2086 # word splitting wanted here
xargs $ARGS
# Custom severity
shellcheck --severity=warning script.sh
shellcheck --shell=bash --check-sourced script.sh
Why it matters
ShellCheck catches 90 percent of bash mistakes. Run it in CI on every shell file in the repo. Suppress with a comment + reason - never globally - so each exception is auditable.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Example
# shellcheck -x script.sh # Catches quoting bugs, [[ vs [ pitfalls, and more.Try it Yourself »
Discussion
Loading…