ShellCheck: Static Analysis for Bash Scripts
ShellCheck is a free, open-source tool that reads a shell script and reports problems in it without running it. It finds the mistakes this tutorial has warned about again and again: unquoted variables that split on spaces, cd commands whose failure is ignored, $? tested too late, read without -r, variables that are assigned but never used, Bash-only syntax in a script meant for sh, and hundreds more. Each problem it reports has a code such as SC2086, a short message, and a page on the ShellCheck wiki that explains the problem and the fix.
Analyzing code without running it is called static analysis. It is especially valuable for shell scripts, because the shell itself reports almost nothing in advance. Bash only notices a problem when the faulty line actually runs, and many problems (an unquoted variable, an ignored failure) never produce an error message at all; they just do the wrong thing when the input is unusual. ShellCheck shows these problems before the script ever touches real data.
Understanding the Concept
When you run bash -n script.sh (lesson 126), Bash checks only the syntax: whether every if has a fi and every quote is closed. A script can pass bash -n and still be full of bugs, because the syntax of this line is perfectly valid:
cd $src
ShellCheck goes further. It parses the script into the same structure the shell would, then applies a large set of rules based on how the shell actually behaves. It knows that an unquoted $src undergoes word splitting and globbing, that cd can fail, and that if it fails, every following command runs in the wrong folder. It reports both problems and points to the exact column where they start.
ShellCheck does not run your script, so it cannot know what values variables will hold or whether files exist. It reports patterns that are wrong or risky in general. That makes it fast and safe to run on any script, but it also means it cannot find logic errors such as a wrong file name or a wrong calculation. It complements testing (lessons 185-187); it does not replace it.
Installing ShellCheck
ShellCheck is packaged for most systems:
sudo apt install shellcheck # Debian, Ubuntu
sudo dnf install ShellCheck # Fedora (note the capital letters)
brew install shellcheck # macOS with Homebrew
pip install shellcheck-py # a Python package that ships the ShellCheck binary
Check the installed version with:
shellcheck --version
Distribution packages are sometimes several versions behind; newer versions add checks and fix suggestions, so a recent version is worth having. If you cannot install anything, the website shellcheck.net runs the same checks on a script you paste into the browser. Do not paste scripts that contain passwords or other secrets into any website.
Running ShellCheck
Pass one or more script files:
shellcheck archive-logs.sh
shellcheck scripts/*.sh
ShellCheck decides which shell dialect to check for from the shebang line. #!/bin/bash and #!/usr/bin/env bash select Bash rules; #!/bin/sh selects POSIX sh rules, under which Bash features such as [[ ]] and arrays are reported. If a file has no shebang (for example, a library that is only ever sourced), ShellCheck reports SC2148 and asks you to name the shell, either with -s bash on the command line or with a directive comment, shown later.
Exit status
ShellCheck's exit status makes it easy to use in scripts and automated checks:
| Status | Meaning |
|---|---|
| 0 | all files checked, no problems found |
| 1 | all files checked, problems found |
| 2 | some files could not be processed (for example, a file was not found) |
| 3 | ShellCheck was called with bad syntax (for example, an unknown option) |
| 4 | ShellCheck was called with bad option values (for example, an unknown format) |
So shellcheck *.sh && echo clean prints clean only when there is nothing to fix.
Reading ShellCheck Output
Here is a short script with several typical problems:
#!/bin/bash
# archive-logs.sh: compress .log files in a folder into an archive folder
src=$1
dest=$2
count=0
cd $src
for f in *.log; do
gzip -c $f > $dest/$f.gz
count=$((count+1))
done
echo "Archived $count files at `date +%H:%M`"
In the default output format, ShellCheck prints each problem under the line it belongs to, with a marker under the exact text and the code, severity and message:
In archive-logs.sh line 6:
cd $src
^-----^ SC2164 (warning): Use 'cd ... || exit' or 'cd ... || return' in case cd fails.
^--^ SC2086 (info): Double quote to prevent globbing and word splitting.
Newer versions add a Did you mean: block with a corrected line for many problems, and every report ends with a list of wiki links, one for each code that appeared, such as https://www.shellcheck.net/wiki/SC2164.
The compact gcc format puts one problem on each line as file:line:column: level: message [code], which is easy to read in a terminal and is understood by many editors:
shellcheck -f gcc archive-logs.sh
For this script the report contains these problems (the exact wording of messages can differ slightly between ShellCheck versions):
archive-logs.sh:6:1: warning: Use 'cd ... || exit' or 'cd ... || return' in case cd fails. [SC2164]
archive-logs.sh:6:4: note: Double quote to prevent globbing and word splitting. [SC2086]
archive-logs.sh:8:11: note: Double quote to prevent globbing and word splitting. [SC2086]
archive-logs.sh:8:15: note: Double quote to prevent globbing and word splitting. [SC2086]
archive-logs.sh:8:21: note: Double quote to prevent globbing and word splitting. [SC2086]
archive-logs.sh:11:32: note: Use $(...) notation instead of legacy backticks `...`. [SC2006]
Columns count from 1. On line 8, gzip -c $f > $dest/$f.gz, column 11 is the first $f, column 15 is $dest and column 21 is the second $f. The gcc format calls both the info and style severities note.
Are these problems real?
It is tempting to treat such reports as style complaints. Running the script shows that they are not. The first version was saved as archive-logs-v1.sh so it can be compared with the fixed version later. Given a source folder whose name contains a space, my logs, holding app.log and web server.log, and started in a folder that happens to contain stray.log:
bash archive-logs-v1.sh "my logs" archive; echo "status $?"
ls archive
archive-logs-v1.sh: line 6: cd: too many arguments
Archived 1 files at 10:56
status 0
stray.log.gz
The unquoted $src split my logs into two arguments, so cd failed (SC2086). Because the failure was not handled, the loop ran in the starting folder and archived the wrong file (SC2164), and the script still reported success with status 0. ShellCheck pointed at exactly these two problems on line 6 before the script was ever run.
Severity Levels
Every check has one of four severities:
| Severity | Meaning | Examples |
|---|---|---|
error | the script will almost certainly not do what you intended | SC2068 unquoted $@ re-splitting array elements, SC2045 iterating over ls output |
warning | likely bugs or risky constructs | SC2164 unchecked cd, SC2034 unused variable, SC2155 local hiding a failure, SC2115 possible rm -rf / |
info | issues that cause bugs only with some inputs | SC2086 unquoted variable, SC2162 read without -r |
style | clearer or more modern ways to write the same thing | SC2006 backticks, SC2181 testing $? instead of the command |
Use -S (or --severity) to report only problems at or above a level:
shellcheck -S warning deploy.sh # errors and warnings only
shellcheck -S error *.sh # errors only
This is useful when you start using ShellCheck on a large, old collection of scripts: fix errors and warnings first, then work down. Note that SC2086 is only info, even though it is the most common cause of real bugs in shell scripts, so do not stop at -S warning for long.
Common Checks and What They Teach
Most ShellCheck reports in real scripts come from a small set of checks. Each one corresponds to Bash behavior explained earlier in this tutorial.
SC2086: Double quote to prevent globbing and word splitting
An unquoted $var is split on whitespace and its pieces are expanded as glob patterns (lessons 53 and 55). Quote it: "$var". When you really want several arguments, use an array ("${opts[@]}") rather than relying on splitting.
SC2164: Use 'cd ... || exit' in case cd fails
After a failed cd, everything else runs in the wrong folder. Write cd "$dir" || exit, or avoid cd and use full paths (lesson 160).
SC2155: Declare and assign separately to avoid masking return values
local, export, declare and readonly return their own status, which hides the status of a command substitution (lesson 117):
f() { local out=$(false); echo "status after local: $?"; }
g() { local out; out=$(false); echo "status after split: $?"; }
f; g
status after local: 0
status after split: 1
The combined form reports success even though the command failed, and set -e does not notice the failure either.
SC2162: read without -r will mangle backslashes
printf 'x\\ty\n' | { read v; echo "read: $v"; }
printf 'x\\ty\n' | { read -r v; echo "read -r: $v"; }
read: xty
read -r: x\ty
Without -r, read removes backslashes (lesson 114).
SC2181: Check exit code directly, not indirectly with $?
cmd; if [ $? -ne 0 ]; then is longer and more fragile than if ! cmd; then, because any command added between the two lines changes $? (lesson 122).
SC2034: variable appears unused
Usually a typo: a variable assigned under one name and used under another. If the variable really is used elsewhere (by a script that sources this one, or by a child process), export it or add a directive explaining why.
Other checks you will meet often
- SC2046
Quote this to prevent word splitting: an unquoted$(command). - SC2068 an unquoted
$@or${array[@]}, which re-splits the elements. - SC2115
rm -rf "$dir/"where$dircould be empty; use"${dir:?}/"(lesson 160). - SC2154 a variable that is used but never assigned, often one that comes from a sourced file.
- SC2006 backticks instead of
$(...)(lesson 48). - SC3xxx codes, reported under
#!/bin/sh, mark Bash features that POSIXshdoes not have; for example,[[ ]]in anshscript (lesson 189).
Every code has its own wiki page at https://www.shellcheck.net/wiki/SC<number>. Reading the page for each new code you meet is one of the quickest ways to learn shell scripting in depth.
Silencing a Check Deliberately
Sometimes a report is a false positive, or the flagged behavior is exactly what you want. ShellCheck reads directives: comments that start with # shellcheck.
A directive placed directly before a command applies to that command only:
# Word splitting is intended: EXTRA_FLAGS holds several simple flags from our own config.
# shellcheck disable=SC2086
rsync -a $EXTRA_FLAGS "$src/" "$dest/"
A directive placed after the shebang, before the first command, applies to the whole file. Several codes can be listed together: # shellcheck disable=SC2034,SC2154.
Always write a comment explaining why a check is disabled. A bare disable hides the reason from the next reader, who cannot tell whether the problem was considered or just silenced. Before disabling SC2086, consider whether an array would remove the need entirely:
extra_flags=(--delete --exclude '*.tmp')
rsync -a "${extra_flags[@]}" "$src/" "$dest/"
Other useful directives:
| Directive | Purpose |
|---|---|
# shellcheck shell=bash | name the dialect for a file with no shebang, such as a sourced library |
# shellcheck source=lib/common.sh | tell ShellCheck which file a source command loads when the path is computed at run time |
# shellcheck source=/dev/null | tell ShellCheck not to follow a source command (for example, a user's own config file) |
# shellcheck disable=SC1091 | ignore "not following" reports for sourced files ShellCheck was not asked to read |
Following sourced files
By default ShellCheck does not open files that a script loads with source or . and reports SC1091 for them. Run it with -x (--external-sources) to follow them, which also lets it see the variables and functions they define, so they are no longer reported as unassigned (SC2154). When a script finds its library relative to its own location (lesson 95), for example source "$SCRIPT_DIR/lib/common.sh", ShellCheck cannot evaluate the path; a # shellcheck source=lib/common.sh directive above the line, combined with -P SCRIPTDIR (--source-path=SCRIPTDIR), tells it where the file is.
A Configuration File
Options that apply to a whole project can go into a file named .shellcheckrc in the project folder (ShellCheck searches the folder of each checked file and its parents) or in your home folder. It contains directives without the # shellcheck prefix:
# .shellcheckrc
# Follow `source` statements and resolve relative source paths from each script's folder
external-sources=true
source-path=SCRIPTDIR
# Our scripts print fixed formats from variables on purpose
disable=SC2059
Keep project-wide disables rare and documented; each one hides that class of bug in every script.
Useful Command-Line Options
| Option | Effect |
|---|---|
-s bash / --shell=bash | check as this dialect (sh, bash, dash, ksh) regardless of the shebang |
-S warning / --severity=warning | report only this severity and above |
-e SC2086,SC2034 / --exclude=... | skip these codes for this run |
-i SC2086 / --include=... | report only these codes |
-x / --external-sources | follow files loaded with source |
-f FORMAT / --format=FORMAT | output as tty (default), gcc, json, json1, checkstyle, diff or quiet |
-o all / --enable=all | turn on optional checks; --list-optional shows them |
-a / --check-sourced | also report problems found in the sourced files |
The diff format prints ShellCheck's automatic fixes as a patch, which can be reviewed and applied with git apply or patch. Only some checks offer automatic fixes, and every patch should be read before it is applied. Lesson 190 shows how to run ShellCheck automatically from editors, Git hooks and CI pipelines.
What ShellCheck Cannot Find
ShellCheck knows the shell, not your intentions. It cannot tell that:
- a script should use
nullglobso that an empty folder does not process the literal text*.log; - a file name, URL or numeric limit is wrong;
- an operation is destructive and needs a dry run or a confirmation;
- a value coming from a user needs validation (lesson 161).
A script with no ShellCheck reports is free of a large class of common shell mistakes. It is not proven correct. Combine ShellCheck with set -euo pipefail (lesson 121), careful input validation and tests.
A Complete Example: Fixing a Script with ShellCheck
Working through the report for archive-logs.sh one problem at a time gives this version:
#!/usr/bin/env bash
# archive-logs.sh: compress .log files in a folder into an archive folder
set -euo pipefail
shopt -s nullglob
src=${1:?usage: archive-logs.sh SRC DEST}
dest=${2:?usage: archive-logs.sh SRC DEST}
count=0
for f in "$src"/*.log; do
gzip -c -- "$f" > "$dest/${f##*/}.gz"
count=$((count + 1))
done
echo "Archived $count files at $(date +%H:%M)"
How It Works
- SC2164 and SC2086 on
cd $src. Instead of quoting and checkingcd, the fixed version removescdentirely and loops over"$src"/*.log. The folder name is quoted, and the glob part stays outside the quotes so it still matches files. Withoutcd, a relativedestfolder also keeps meaning "relative to where the script was started". - SC2086 on line 8. Every expansion is quoted.
${f##*/}takes the file name without the folder (lesson 54), so the archive gets the nameapp.log.gzrather than a path.--stopsgzipfrom reading a file named-v.logas an option. - SC2006. The backticks became
$(date +%H:%M). - Beyond ShellCheck.
set -euo pipefailstops the script whengzipfails or a variable is misspelled.${1:?...}gives a usage message when an argument is missing.shopt -s nullglobmakes the loop run zero times for an empty folder instead of trying to compress a file literally named*.log. ShellCheck does not ask for these; they come from the rest of this tutorial.
The fixed file no longer contains any of the patterns ShellCheck reported. When a check of the whole file comes back empty, shellcheck exits with status 0.
Running the Complete Example
The same inputs that broke the first version:
bash archive-logs.sh "my logs" archive; echo "status $?"
ls archive
Archived 2 files at 10:56
status 0
app.log.gz
stray.log.gz
web server.log.gz
Both files in my logs were archived, including the one with a space in its name. (stray.log.gz is left over from the run of the first version.) An empty folder and missing arguments are handled clearly:
bash archive-logs.sh empty archive; echo "status $?"
bash archive-logs.sh; echo "status $?"
Archived 0 files at 10:56
status 0
archive-logs.sh: line 6: 1: usage: archive-logs.sh SRC DEST
status 1
The habit to build is simple: run shellcheck on every script before you run the script itself, read the wiki page for every code you do not recognize, and fix the cause rather than silencing the message.