ShellCheck: Catching the Bash Bug Before It Catches You
A linter that reads your script the way an experienced sysadmin reads it, and tells you exactly which line is going to bite

Contents
Somewhere in my early homelab years I wrote a cleanup script that deleted a directory tree based on a variable that happened to be empty on that particular run, because an earlier command had failed silently and the script didn’t check. rm -rf "$dir"/* with an unset $dir doesn’t fail loudly, it expands to rm -rf /* behind sudo’s permissions, and only stopped because I’d actually quoted it and a permissions error on / broke the loop early. That single quoting habit is the only reason that script’s story is an anecdote and not a restore-from-backup afternoon. ShellCheck exists specifically to catch that class of mistake before you run the script, and once you’ve used it seriously it becomes uncomfortable to write bash without it. What makes the incident sting in hindsight is that the bug wasn’t exotic. It’s one of the first checks ShellCheck runs on any script you point it at, and it would have flagged that exact line, with the exact fix, before I ever ran it against a real filesystem.
What ShellCheck actually is
ShellCheck is a static analysis tool for shell scripts, sh, bash, dash and ksh all included, that parses your script and flags constructs that are syntactically valid but semantically dangerous or almost certainly not what you meant. ShellCheck goes well past a style linter complaining about indentation: the overwhelming majority of its checks catch behaviour that only shows up under specific, often rare, input conditions, which is exactly the kind of bug that’s cheap to introduce and expensive to debug after the fact, because it usually works fine in every test you happen to run and fails on the one input you didn’t think to try.

Running it is as direct as it gets:
| |
Every warning comes with an SC-numbered code, a plain-English explanation, and in most cases a suggested fix, which matters because it turns ShellCheck from a tool you have to already understand shell pitfalls to benefit from into one that actively teaches you them as you go.
The one check that matters more than the rest: SC2086
If you only internalise a single ShellCheck rule, make it SC2086: quote your variables. Unquoted variable expansion in bash goes through word splitting and globbing before the result reaches the command, which is almost never what you want and is the single most common source of real bash bugs. Word splitting means bash breaks an unquoted expansion on whitespace, so a filename with a space in it silently becomes two arguments instead of one. Globbing means an unquoted expansion containing shell metacharacters like * gets expanded against the filesystem before the command ever sees it.
| |
The rm -rf example at the top of this post is the same bug with worse consequences: an empty, unset $target in rm -rf $target/* doesn’t error, it word-splits into nothing, leaving rm -rf /*, which is a very different command from the one you wrote. "$target"/* with the quotes in place instead fails to match anything and exits harmlessly, or at minimum operates on the literal empty-string path rather than root. Quoting every variable expansion by default, and only leaving one unquoted when you specifically want word splitting or globbing to happen, eliminates most of the scary bash failure modes in one habit.
Beyond quoting: the checks that catch logic bugs
SC2086 gets the headline because it’s the most common and most dangerous, but ShellCheck’s real depth is in checks that catch logic errors that have nothing to do with quoting.
SC2181, checking $? after the fact instead of checking the command directly, flags code like:
| |
which works but is fragile, because $? reflects whichever command ran most recently, and it’s easy to accidentally insert a line between the check and the command it was meant to check. ShellCheck suggests testing the command’s exit status directly: if grep pattern file; then, which is both shorter and immune to that class of accidental insertion bug.
SC2046, unquoted command substitution, catches the same word-splitting problem as SC2086 but applied to $(...) output rather than a plain variable, which is easy to miss because command substitution doesn’t look like a variable at first glance:
| |
SC2164, cd without checking whether it succeeded, catches a pattern that’s easy to write and dangerous specifically inside scripts that then do something destructive relative to the current directory:
| |
If that cd fails, the following rm runs from wherever the script actually started, not the path you intended, which is the same shape of disaster as the unquoted rm example, arrived at through a completely different mistake. ShellCheck’s suggested fix, cd /some/path || exit 1, stops the script cold the moment the assumption it depends on turns out to be false.
A few more checks worth knowing by number
Beyond the headline three, a handful of other SC codes come up often enough in ordinary scripts to be worth recognising on sight rather than looking up each time.
SC2006, backtick command substitution instead of $(...), is mostly a readability and nesting issue rather than a correctness one: backticks can’t be nested without escaping, `echo \`date\ `` versus the far more legible $(echo $(date)), and ShellCheck flags every backtick pair as a nudge toward the modern syntax, which is worth taking even in scripts old enough to predate the convention.
SC2128, using an array variable in a context that only sees its first element, catches a genuinely confusing failure mode: echo "$my_array" where my_array is a bash array doesn’t print the whole array or error, it silently prints only element zero, which looks like a working command that’s quietly wrong. The fix is "${my_array[@]}" to expand every element as separate words, or "${my_array[*]}" to join them into one string, and ShellCheck’s warning is often the first sign a script has been treating an array like a scalar without anyone noticing.
SC2115, rm -rf "$STEPS"/* where $STEPS is unset or empty, is functionally the same danger as the SC2086 example earlier but ShellCheck flags it as its own dedicated check specifically for path-deletion patterns, because the failure mode, deleting far more than intended, is severe enough to warrant a check that doesn’t depend on the variable being unquoted at all; even a quoted but empty "$STEPS"/* deletes everything in the current directory, and ShellCheck catches that shape directly.
Running it in CI, where every contributor is covered
A pre-commit hook only protects commits made from a machine that has the hook installed, which is every machine you personally use and none of the ones a collaborator or a future you on a fresh laptop hasn’t set up yet. Running ShellCheck as an explicit CI step closes that gap, failing the build the same way a failed test would rather than relying on everyone remembering to lint locally first:
| |
Once this step exists once, it’s exactly the kind of small, repeated CI logic worth packaging as a reusable step rather than pasting the same three lines into every repository that ships shell scripts, since the find/xargs invocation and the install step are identical everywhere they’re needed.
Running it as a habit, built into your workflow
shellcheck as a one-off command you run when you remember to catches bugs eventually, but the actual value is in making it impossible to forget. A pre-commit hook is the lowest-friction way to get there, checking every staged shell script before a commit is allowed to land:
| |
For scripts embedded inline in CI configuration rather than living in their own .sh files, ShellCheck can’t reach them directly, but it’s worth extracting anything beyond a couple of lines into a real script file specifically so it can be linted, which is a good discipline independent of ShellCheck: a script that’s easy to lint is also a script that’s easy to test locally, outside whatever pipeline eventually runs it.
Most editors also have ShellCheck integration through the Language Server Protocol, underlining problem lines the moment you write them rather than waiting for a save-and-run cycle, which is where the tool stops feeling like a gate you pass through and starts feeling like autocomplete for correctness.
When to silence a warning instead of fixing it
Not every warning deserves a code change; ShellCheck is deliberately cautious and sometimes flags something you’ve genuinely thought through. # shellcheck disable=SC2086 on the line above the offending code, or a SC2086 reference in a # shellcheck disable=SC2086,SC2046 comment covering the whole file, suppresses a specific check with a specific, visible justification living right next to the code it applies to. The discipline worth keeping here is narrow suppression: disable the one code that doesn’t apply on the one line it doesn’t apply to, with a comment explaining why, rather than reaching for a blanket # shellcheck disable=all at the top of the file, which silences everything the tool would have caught on every future edit to that script, not just the line you were looking at when you wrote the suppression.
A common legitimate case is intentional word splitting: a variable holding space-separated flags that you genuinely want split into separate arguments, options="-v --dry-run"; rsync $options source dest. ShellCheck will flag the unquoted $options, and the fix here isn’t quoting, since quoting would pass the whole string as one argument and break the command; it’s either an explicit disable comment explaining the intent, or restructuring the variable as a bash array from the start, options=(-v --dry-run); rsync "${options[@]}" source dest, which sidesteps the ambiguity entirely by making the splitting explicit in the data structure rather than implicit in unquoted expansion.
Troubleshooting: when ShellCheck disagrees with a script that “works”
The most common friction point is a script that’s run successfully for years suddenly lighting up with a dozen warnings the first time someone points ShellCheck at it. That’s a sign the script has been getting lucky on every input it happened to be run against so far, rather than the tool being pedantic. Work through the warnings in severity order, ShellCheck labels each as error, warning, info or style, and fix the error and warning tier first, since those are the categories most likely to represent an actual latent bug rather than a stylistic preference.
If ShellCheck reports a false positive against code you’re confident is correct, check the shell dialect it’s assuming first; running shellcheck -s bash explicitly, or adding a #!/usr/bin/env bash shebang ShellCheck can read, matters because some warnings only apply to POSIX sh and don’t apply to bash-specific syntax, and ShellCheck defaults to inferring the dialect from the shebang line, which produces confusing false positives if the shebang is missing, wrong, or the script is being piped in without a file at all. A related trap is a script that’s genuinely meant to run under POSIX sh for portability, where ShellCheck will correctly flag bash-only syntax, arrays, [[ ]] conditionals, local in some dialects, as errors precisely because that syntax doesn’t exist in the dialect the shebang declares. If a warning here surprises you, it usually means the shebang says one thing and the syntax in the body assumes another, and the fix is to make them agree rather than to silence the warning.
Is it worth adding to every script
Yes, without much of a caveat. The setup cost is a single package install and, at most, a five-line pre-commit hook, and the payoff is catching the exact category of bug that’s invisible in testing and catastrophic in production: unquoted expansions, unchecked exit codes, cd failures that silently relocate a destructive command. It pairs naturally with bash strict mode, since strict mode makes a script fail loudly on the errors ShellCheck didn’t catch, and ShellCheck catches the mistakes strict mode’s blunt instrument would otherwise let through unnoticed. If you write bash scripts you intend to still trust in a year, run ShellCheck against them now rather than after the first one does something you didn’t ask for.




