Static Analysis with ShellCheck

Static Analysis with ShellCheck in Bash: A pressure-vessel shop welds heavy steel drums that will one day hold gas at many times atmospheric pressure.

The Analogy: The Radiographic Weld-Inspection Bay

A pressure-vessel shop welds heavy steel drums that will one day hold gas at many times atmospheric pressure. Before any vessel is certified, every welded seam has to be inspected -- but you cannot judge a weld by looking at its surface, and you certainly cannot pressurize the vessel just to see whether the seam holds. So the drum is wheeled into the radiographic bay. A radiation source sits on one side of the seam and a film or digital detector on the other, and the weld is photographed from the inside out. What comes back is an image of the metal's interior: the grain, the fusion line, and any voids hiding where no eye could reach.

The inspector reads that image against a code book. Every kind of flaw has a name and a designation -- porosity, slag inclusion, lack of fusion, undercut, a crack -- and every indication is marked with its type, its position along the seam, and a severity: acceptable as is, must be ground out and re-welded, or outright reject. The report names the weld and the defect; it does not describe the whole vessel. Crucially, none of this loads the seam. The weld is never stressed to find its flaw; it is read, cold and static, from an image.

The value of the bay is that it catches, cheaply and repeatably, defects that would otherwise surface only in service -- under pressure, under fatigue, at three in the morning in a plant far away. A flaw found on film is ground out and re-welded, and the seam is simply photographed again. The shop can set its acceptance thresholds too: a little scattered porosity may be tolerable in a low-duty tank, while a nuclear-grade vessel is held to a far stricter standard. The same seam, the same image, judged against the bar the job demands.

But the radiograph is not omniscient, and reading it as a guarantee is the trap. The method sees changes in density well, yet a tight planar crack lying edge-on to the beam can hide in plain sight, and no film says a word about whether the vessel was designed for the right pressure in the first place. A seam can pass every exposure and the drum can still burst under a load case the inspection never simulated. Passing means only "none of the flaw classes this method detects were present," not "fit for every duty." Trust the clean image as proof of service life and the defect the film could not see rides out of the shop inside a certified vessel.


Syntax or Core Structure

ShellCheck is the radiographic bay for shell scripts. It reads your script as text and reports likely bugs and portability problems without ever running it -- no load applied, no side effects, just an image of the code's interior. Every finding carries a code such as SC2086, a severity, a line and column, and a one-line explanation that links to a wiki page. You run it by handing it a file:

shellcheck script.sh

The flagship finding is SC2086: an expansion left unquoted, which the shell will split on whitespace and expand as a glob. Here is a script that trips it, printed with the stable gcc output format (file:line:column: severity: message [code]), which is easier to read and to parse than the default caret layout:

#!/usr/bin/env bash
msg="hello   world"
echo $msg
shellcheck -f gcc greet.sh

Output:

greet.sh:3:6: note: Double quote to prevent globbing and word splitting. [SC2086]

(ShellCheck is a separate tool, not part of Bash; the reports in this lesson use its gcc format, and the codes and messages shown are stable across versions. A note in this format is ShellCheck's info or style severity.)

The finding is not pedantry. Run the script and the unquoted expansion collapses the three spaces, because the shell splits $msg into words and rejoins them with one space; quote it and the value survives intact:

#!/usr/bin/env bash
msg="hello   world"
echo $msg
echo "$msg"

Output:

hello world
hello   world

That is exactly the kind of latent fault the radiograph is for: the script "works" on a tidy value and quietly corrupts one with spaces or a * in it. ShellCheck sees the flaw in the image, before any input loads the seam.


Technical Depth: Reading the Report and Tuning the Beam

The severity ladder

Every finding has one of four severities. They rank how confident ShellCheck is that something is actually wrong, from a definite fault down to a matter of taste. The gcc format collapses the lower two onto the label note:

SeverityMeaninggcc labelExample code
errorA definite fault; parsing may stoperrorSC2148
warningA likely bugwarningSC2164
infoA correctness suggestionnoteSC2086
styleA cleanliness or portability nitnoteSC2006

The common codes

A handful of codes account for most of what ShellCheck says about everyday scripts. Knowing them by sight turns a wall of findings into a quick triage:

CodeSeverityWhat it flags
SC2086infoAn unquoted variable expansion
SC2046warningAn unquoted command substitution
SC2164warningA cd whose failure is not handled
SC2006styleLegacy backtick command substitution
SC2034warningA variable assigned but never used
SC2181styleChecking the exit code through a variable
SC2148errorNo shebang, so the shell is unknown
SC2162infoA read without -r, which mangles backslashes

Two of these show up constantly. An unguarded cd earns SC2164, because if the directory is missing the script barrels on in the wrong place:

shellcheck -f gcc nav.sh

Output:

nav.sh:2:1: warning: Use 'cd ... || exit' or 'cd ... || return' in case cd fails. [SC2164]

A variable you assign and never read earns SC2034 -- often a sign of a typo in the name you use later:

shellcheck -f gcc theme.sh

Output:

theme.sh:2:1: warning: color appears unused. Verify use (or export if used externally). [SC2034]

Choosing what to see

Two flags tune the beam. -S sets the minimum severity reported: -S error shows only errors, -S warning hides info and style, and the default reports everything down to style. -f picks the output format: tty is the default caret layout, gcc is the compact one used here, and json or checkstyle feed other tools. The one you must not miss is the exit status: ShellCheck exits 0 when nothing is reported at or above the threshold and 1 when it finds something. That single bit is what lets a build gate on a clean report.

A clean script prints nothing and exits zero:

shellcheck -f gcc clean.sh; echo "status: $?"

Output:

status: 0

A flawed one prints its findings and exits one, so && or set -e in a pipeline will stop on it:

shellcheck -f gcc greet.sh; echo "status: $?"

Output:

greet.sh:3:6: note: Double quote to prevent globbing and word splitting. [SC2086]
status: 1

Silencing a check on purpose

Sometimes a finding is a false alarm for your situation, and you want to acknowledge it rather than obey it. A # shellcheck disable=SC2086 comment on the line above a command suppresses that code for that command; placed just after the shebang it applies to the whole file. Here the directive silences the unquoted-expansion warning, so the run is clean:

#!/usr/bin/env bash
# shellcheck disable=SC2086
msg="a b"
echo $msg
shellcheck -f gcc t.sh; echo "status: $?"

Output:

status: 0

Use this sparingly and scope it to a single line with a comment saying why. A blanket disable at the top of a file is the equivalent of taping over the amber lamp: the next real fault of that class rolls straight through unseen.


Real World Example: A Lint-Clean Log Summarizer

The script below walks a directory of log files and prints a line count for each, then a total. It did not start this tidy. The first draft used cd with no failure handling, expanded $dir and the filenames unquoted, and looped over a glob with no guard for the no-match case -- ShellCheck flagged SC2164, SC2086, and a bare-glob risk on the very first run. The version here is what came out the other side: every expansion quoted, the cd guarded, and the empty-directory case handled, so a fresh ShellCheck run reports nothing.

#!/usr/bin/env bash
# tidy-logs.sh -- summarize .log files in a directory, safely quoted throughout
set -euo pipefail

dir="${1:?usage: tidy-logs.sh DIR}"

cd "$dir" || exit 1

total=0
for f in *.log; do
  [ -e "$f" ] || continue
  lines=$(wc -l < "$f")
  echo "$f: $lines lines"
  total=$((total + lines))
done

echo "total: $total lines"

Point it at a directory holding access.log (2 lines), app.log (3 lines), and error.log (1 line), and it walks them in sorted order and tallies the total:

bash tidy-logs.sh logs

Output:

access.log: 2 lines
app.log: 3 lines
error.log: 1 lines
total: 6 lines

Now run the radiograph over the script itself. Nothing is printed and the status is zero, the seam is clean:

shellcheck -f gcc tidy-logs.sh; echo "status: $?"

Output:

status: 0

Read the script against the codes it once tripped. ${1:?...} refuses to run without a directory argument, so the cd never fires blind. The cd "$dir" || exit 1 clears SC2164: a missing directory stops the script instead of letting it summarize the wrong place. Every expansion -- "$dir", "$f", "$lines" -- is quoted, clearing SC2086, so a log file named with a space is counted as one file, not split into two. And [ -e "$f" ] || continue handles the case where the glob matches nothing and is left as the literal string *.log.

Because those whole classes of fault are gone, a fresh ShellCheck run reports nothing and exits zero. That is precisely what a CI gate keys on: the summarizer can sit behind a rule that blocks any merge whose scripts do not pass the inspection, and this one passes cold, every time, without being run against real inputs.

What the clean image does not certify is that the script is correct. ShellCheck checks form, not intent, so it says nothing about the plain "1 lines" that should read "1 line" -- grammar is invisible to it. It cannot know that wc -l counts newline characters, so a final line with no trailing newline is silently undercounted, an off-by-one no static check will catch. Nor does it flag that the cd is one-way: grow the script to sweep several directories and it will summarize them all relative to the first. The welds are sound; whether the vessel suits its duty is a question the film was never able to answer.


Common Mistakes

  1. Reading a clean run as "bug-free." ShellCheck reports the flaw classes it knows how to detect, not the absence of all bugs. A script can pass with zero findings and still have broken logic, a wrong algorithm, or a runtime-only failure. A clean radiograph means no detectable flaws, not fitness for duty.
  1. Dismissing info and style findings as noise. The most common real bug of all, the unquoted expansion behind SC2086, is only info severity. Filtering with -S warning to quiet the report hides exactly the findings that catch everyday word-splitting and globbing faults.
  1. Blanket-disabling a code at the top of the file. A file-wide # shellcheck disable silences that check everywhere, including the next place it would have caught a genuine bug. Scope the directive to the single line you have deliberately made safe, and say why in a comment.
  1. Leaving off the shebang. With no #! line and no shell directive, ShellCheck cannot tell whether you mean sh, bash, or something else, raises SC2148, and skips the dialect-specific checks. You lose coverage precisely where portability bugs live.
  1. Running ShellCheck only by hand. A check you remember to run occasionally does not stop regressions. Without it wired into CI or a pre-commit hook, a freshly introduced unquoted expansion sails into the main branch between manual passes.
  1. Treating the line and column as the fix. The location points at the symptom, not always the cause. A SC2154 "referenced but not assigned" often means a typo in the assignment three lines up; read the linked wiki entry rather than editing blindly at the caret.
  1. "Fixing" a finding by deleting the variable. Silencing SC2086 by removing the expansion, or SC2034 by deleting an assignment you actually needed, trades a warning for a behavior change. Quote the expansion or use the variable; do not amputate the code to quiet the tool.
  1. Assuming ShellCheck follows sourced files. By default it does not read the files a script sources; it raises SC1091 and analyzes only the current file. Point it at the sourced paths, or accept that definitions from those files are invisible to the check.
  1. Raising the severity threshold to get a clean report. Passing -S error so the build goes green does not fix anything; it just stops the bay from showing you the warnings and infos. A green light you bought by turning off the lamps is worse than no light at all.

Best Practices

  • Run ShellCheck in continuous integration, not just at your desk. Wire it into the pipeline and gate merges on a clean, zero-exit report. A check that depends on someone remembering to run it will be skipped on exactly the busy day a bug ships.
  • Fix the cause, not the caret. Every finding links to a wiki page explaining the class of bug. Read it before you edit; the line and column mark the symptom, and the real fault is often a few lines away.
  • Quote every expansion by default. Quoting clears SC2086 and SC2046 and stops word-splitting and globbing before they corrupt an argument. When you genuinely want several words, use an array, not an unquoted expansion.
  • Give every script a shebang. A #! line tells ShellCheck which dialect to assume, clears SC2148, and unlocks the shell-specific checks. Without it you lose coverage on the portability bugs that matter most.
  • Scope disable directives to a single line, with a reason. When you must override a finding, put the # shellcheck disable directly above the one command and add a comment justifying it. Never blanket-disable a code across a whole file.
  • Keep the default severity threshold. Leave the report showing style and info findings; they include the most common real bug there is. Raise the bar only for a specific, documented reason, never just to turn a build green.
  • Pair static analysis with a syntax check and real tests. Run bash -n for parse errors and a test suite for behavior alongside ShellCheck. The three nets catch different failures, and none of them is a substitute for the others.
  • Treat a clean report as a floor, not a ceiling. Zero findings means no detectable flaws of the known classes, not correctness. Pair the inspection with review and testing for the logic errors the film was never able to see.

Practice Exercises

  1. Quote the splitters. Write a script containing cp $src $dst and run it with a filename that has a space in it to watch it fail; then run ShellCheck to see SC2086, quote both expansions, and confirm that both the runtime failure and the finding are gone.
  1. Read the ladder. Craft a script that triggers one finding at each severity you can reach -- an error from a missing shebang, a warning from an unguarded cd, an info from an unquoted variable, a style nit from legacy backticks -- then run it with -S warning and explain exactly which findings vanish and why.
  1. Scope a disable. Take a line ShellCheck flags that you have deliberately made safe, add a # shellcheck disable directive for just that line with a justifying comment, and confirm the report is clean; then move the directive to the top of the file and describe the bug the wider scope could now hide.
  1. Gate a directory. Write a wrapper that runs ShellCheck over every .sh file in a directory, prints one PASS or FAIL line per file, and exits non-zero if any file has findings. Test it against one clean script and one flawed script, and verify the wrapper's own exit status matches.