ShellCheck: Static Analysis for Bash Scripts

Su Suriya Ravichandran Updated 06 Dec 2026
14 min read ·Lesson 162 of 205

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:

StatusMeaning
0all files checked, no problems found
1all files checked, problems found
2some files could not be processed (for example, a file was not found)
3ShellCheck was called with bad syntax (for example, an unknown option)
4ShellCheck 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:

SeverityMeaningExamples
errorthe script will almost certainly not do what you intendedSC2068 unquoted $@ re-splitting array elements, SC2045 iterating over ls output
warninglikely bugs or risky constructsSC2164 unchecked cd, SC2034 unused variable, SC2155 local hiding a failure, SC2115 possible rm -rf /
infoissues that cause bugs only with some inputsSC2086 unquoted variable, SC2162 read without -r
styleclearer or more modern ways to write the same thingSC2006 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 $dir could 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 POSIX sh does not have; for example, [[ ]] in an sh script (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:

DirectivePurpose
# shellcheck shell=bashname the dialect for a file with no shebang, such as a sourced library
# shellcheck source=lib/common.shtell ShellCheck which file a source command loads when the path is computed at run time
# shellcheck source=/dev/nulltell ShellCheck not to follow a source command (for example, a user's own config file)
# shellcheck disable=SC1091ignore "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

OptionEffect
-s bash / --shell=bashcheck as this dialect (sh, bash, dash, ksh) regardless of the shebang
-S warning / --severity=warningreport only this severity and above
-e SC2086,SC2034 / --exclude=...skip these codes for this run
-i SC2086 / --include=...report only these codes
-x / --external-sourcesfollow files loaded with source
-f FORMAT / --format=FORMAToutput as tty (default), gcc, json, json1, checkstyle, diff or quiet
-o all / --enable=allturn on optional checks; --list-optional shows them
-a / --check-sourcedalso 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 nullglob so 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 checking cd, the fixed version removes cd entirely and loops over "$src"/*.log. The folder name is quoted, and the glob part stays outside the quotes so it still matches files. Without cd, a relative dest folder 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 name app.log.gz rather than a path. -- stops gzip from reading a file named -v.log as an option.
  • SC2006. The backticks became $(date +%H:%M).
  • Beyond ShellCheck. set -euo pipefail stops the script when gzip fails or a variable is misspelled. ${1:?...} gives a usage message when an argument is missing. shopt -s nullglob makes 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.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about ShellCheck: Static Analysis for Bash Scripts and get answers drawn from it.

Signed-in readers only.