- Notifications
You must be signed in to change notification settings - Fork1.9k
ShellCheck, a static analysis tool for shell scripts
License
koalaman/shellcheck
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
ShellCheck is a GPLv3 tool that gives warnings and suggestions for bash/sh shell scripts:
The goals of ShellCheck are
To point out and clarify typical beginner's syntax issues that cause a shellto give cryptic error messages.
To point out and clarify typical intermediate level semantic problems thatcause a shell to behave strangely and counter-intuitively.
To point out subtle caveats, corner cases and pitfalls that may cause anadvanced user's otherwise working script to fail under future circumstances.
Seethe gallery of bad code for examples of what ShellCheck can help you identify!
- How to use
- Installing
- Compiling from source
- Gallery of bad code
- Testimonials
- Ignoring issues
- Reporting bugs
- Contributing
- Copyright
- Other Resources
There are a number of ways to use ShellCheck!
Paste a shell script onhttps://www.shellcheck.net for instant feedback.
ShellCheck.net is always synchronized to the latest git commit, and is the easiest way to give ShellCheck a go. Tell your friends!
Runshellcheck yourscript in your terminal for instant output, as seen above.
You can see ShellCheck suggestions directly in a variety of editors.
Sublime, throughSublimeLinter.
Pulsar Edit (former Atom), throughlinter-shellcheck-pulsar.
VSCode, throughvscode-shellcheck.
Most other editors, throughGCC error compatibility.
While ShellCheck is mostly intended for interactive use, it can easily be added to builds or test suites.It makes canonical use of exit codes, so you can just add ashellcheck command as part of the process.
For example, in a Makefile:
check-scripts:# Fail if any of these files have warnings shellcheck myscripts/*.sh
or in a Travis CI.travis.yml file:
script:# Fail if any of these files have warnings -shellcheck myscripts/*.sh
Services and platforms that have ShellCheck pre-installed and ready to use:
- Travis CI
- Codacy
- Code Climate
- Code Factor
- Codety via theCodety Scanner
- CircleCI via theShellCheck Orb
- Github (only Linux)
- Trunk Code Quality (universal linter;allows you to explicitly version your shellcheck install) via theshellcheck plugin
- CodeRabbit
Most other services, includingGitLab, let you installShellCheck yourself, either through the system's package manager (seeInstalling),or by downloading and unpacking abinary release.
It's a good idea to manually install a specific ShellCheck version regardless. This avoidsany surprise build breaks when a new version with new warnings is published.
For customized filtering or reporting, ShellCheck can output simple JSON, CheckStyle compatible XML,GCC compatible warnings as well as human readable text (with or without ANSI colors). See theIntegration wiki page for more documentation.
The easiest way to install ShellCheck locally is through your package manager.
On systems with Cabal (installs to~/.cabal/bin):
cabal updatecabal install ShellCheckOn systems with Stack (installs to~/.local/bin):
stack updatestack install ShellCheckOn Debian based distros:
sudo apt install shellcheckOn Arch Linux based distros:
pacman -S shellcheckor get the dependency freeshellcheck-bin from the AUR.
On Gentoo based distros:
emerge --ask shellcheckOn EPEL based distros:
sudo yum -y install epel-releasesudo yum install ShellCheckOn Fedora based distros:
dnf install ShellCheckOn FreeBSD:
pkg install hs-ShellCheckOn macOS (OS X) with Homebrew:
brew install shellcheckOr with MacPorts:
sudo port install shellcheckOn OpenBSD:
pkg_add shellcheckOn openSUSE
zypper in ShellCheckOr use OneClickInstall -https://software.opensuse.org/package/ShellCheck
On Solus:
eopkg install shellcheckOn Windows (viachocolatey):
C:\> choco install shellcheckOr Windows (viawinget):
C:\> winget install --id koalaman.shellcheckOr Windows (viascoop):
C:\> scoop install shellcheckFromconda-forge:
conda install -c conda-forge shellcheckFrom Snap Store:
snap install --channel=edge shellcheckFrom Docker Hub:
docker run --rm -v"$PWD:/mnt" koalaman/shellcheck:stable myscript# Or :v0.4.7 for that version, or :latest for daily builds
or usekoalaman/shellcheck-alpine if you want a larger Alpine Linux based image to extend. It works exactly like a regular Alpine image, but has shellcheck preinstalled.
Using thenix package manager:
nix-env -iA nixpkgs.shellcheck
Using theFlox package manager
flox install shellcheck
Alternatively, you can download pre-compiled binaries for the latest release here:
- Linux, x86_64 (statically linked)
- Linux, armv6hf, i.e. Raspberry Pi (statically linked)
- Linux, aarch64 aka ARM64 (statically linked)
- macOS, aarch64
- macOS, x86_64
- Windows, x86
or see theGitHub Releases for other releases(including thelatest meta-release for daily git builds).
There are currently no official binaries for Apple Silicon, but third party builds are available viaShellCheck for Visual Studio Code.
Distro packages already come with aman page. If you are building from source, it can be installed with:
pandoc -s -f markdown-smart -t man shellcheck.1.md -o shellcheck.1sudo mv shellcheck.1 /usr/share/man/man1
To run ShellCheck viapre-commit, add the hook to your.pre-commit-config.yaml:
repos:- repo: https://github.com/koalaman/shellcheck-precommit rev: v0.7.2 hooks: - id: shellcheck# args: ["--severity=warning"] # Optionally only show errors and warningsTravis CI has now integrated ShellCheck by default, so you don't need to manually install it.
If you still want to do so in order to upgrade at your leisure or ensure you'reusing the latest release, follow the steps below to install a binary version.
The pre-compiled binaries come intar.xz files. To decompress them, make surexz is installed.On Debian/Ubuntu/Mint, you canapt install xz-utils.On Redhat/Fedora/CentOS,yum -y install xz.
A simple installer may do something like:
scversion="stable"# or "v0.4.7", or "latest"wget -qO-"https://github.com/koalaman/shellcheck/releases/download/${scversion?}/shellcheck-${scversion?}.linux.x86_64.tar.xz"| tar -xJvcp"shellcheck-${scversion}/shellcheck" /usr/bin/shellcheck --version
This section describes how to build ShellCheck from a source directory. ShellCheck is written in Haskell and requires 2GB of RAM to compile.
ShellCheck is built and packaged using Cabal. Install the packagecabal-install from your system's package manager (with e.g.apt-get,brew,emerge,yum, orzypper).
On macOS (OS X), you can do a fast install of Cabal using brew, which takes a couple of minutes instead of more than 30 minutes if you try to compile it from source.
$ brew install cabal-installOn MacPorts, the package is instead calledhs-cabal-install, while native Windows users should install the latest version of the Haskell platform fromhttps://www.haskell.org/platform/
Verify thatcabal is installed and update its dependency list with
$ cabal updategit clone this repository, andcd to the ShellCheck source directory to build/install:
$ cabal installThis will compile ShellCheck and install it to your~/.cabal/bin directory.
Add this directory to yourPATH (for bash, add this to your~/.bashrc):
export PATH="$HOME/.cabal/bin:$PATH"
Log out and in again, and verify that your PATH is set up correctly:
$ which shellcheck~/.cabal/bin/shellcheckOn native Windows, thePATH should already be set up, but the systemmay use a legacy codepage. Incmd.exe,powershell.exe and Powershell ISE,make sure to use a TrueType font, not a Raster font, and set the activecodepage to UTF-8 (65001) withchcp:
chcp65001
In Powershell ISE, you may need to additionally update the output encoding:
[Console]::OutputEncoding= [System.Text.Encoding]::UTF8
To run the unit test suite:
$ cabal testSo what kind of things does ShellCheck look for? Here is an incomplete list of detected issues.
ShellCheck can recognize several types of incorrect quoting:
echo$1# Unquoted variablesfind. -name*.ogg# Unquoted find/grep patternsrm"~/my file.txt"# Quoted tilde expansionv='--verbose="true"'; cmd$v# Literal quotes in variablesforfin"*.ogg"# Incorrectly quoted 'for' loopstouch$@# Unquoted $@echo'Don't forget to restart!' # Singlequote closed by apostropheecho'Don\'t try this at home' # Attempting to escape'in''echo'Path is $PATH'# Variables in single quotestrap"echo Took${SECONDS}s" 0# Prematurely expanded trapunset var[i]# Array index treated as glob
ShellCheck can recognize many types of incorrect test statements.
[[ n!= 0 ]]# Constant test expressions[[-e*.mpg ]]# Existence checks of globs[[$foo==0 ]]# Always true due to missing spaces[[-n"$foo" ]]# Always true due to literals[[$foo=~"fo+" ]]# Quoted regex in =~[ foo=~ re ]# Unsupported [ ] operators[$1-eq"shellcheck" ]# Numerical comparison of strings[$n&&$m ]# && in [ .. ][ grep -q foo file ]# Command without $(..)[["$$file"==*.jpg ]]# Comparisons that can't succeed((1-lt2))# Using test operators in ((..))[ x ]& [ y ]| [ z ]# Accidental backgrounding and piping
ShellCheck can recognize instances where commands are used incorrectly:
grep'*foo*' file# Globs in regex contextsfind. -exec foo {}&& bar {}\;# Prematurely terminated find -execsudoecho'Var=42'> /etc/profile# Redirecting sudotime --format=%s sleep 10# Passing time(1) flags to time builtinwhileread h;do ssh"$h" uptime# Commands eating while loop inputalias archive='mv $1 /backup'# Defining aliases with argumentstr -cd'[a-zA-Z0-9]'# [] around ranges in trexec foo;echo"Done!"# Misused 'exec'find -name\*.bak -o -name\*~ -delete# Implicit precedence in find# find . -exec foo > bar \; # Redirections in findf() { whoami; }; sudo f# External use of internal functions
ShellCheck recognizes many common beginner's syntax errors:
var = 42# Spaces around = in assignments$foo=42# $ in assignmentsfor$varin*;do ...# $ in for loop variablesvar$n="Hello"# Wrong indirect assignmentecho${var$n}# Wrong indirect referencevar=(1, 2, 3)# Comma separated arraysarray=( [index] = value )# Incorrect index initializationecho$var[14]# Missing {} in array referencesecho"Argument 10 is$10"# Positional parameter misreferenceif$(myfunction);then ..;fi# Wrapping commands in $()elseif othercondition;then ..# Using 'else if'f;f() {echo"hello world; } # Using function before definition[ false ] # 'false' being trueif ( -f file ) # Using (..) instead of test
ShellCheck can make suggestions to improve style:
[[-z$(find /tmp| grep mpg) ]]# Use grep -q insteada>> log; b>> log; c>> log# Use a redirection block insteadecho"The time is`date`"# Use $() insteadcd dir; process*;cd ..;# Use subshells insteadecho $[1+2]# Use standard $((..)) instead of old $[]echo$(($RANDOM%6))# Don't use $ on variables in $((..))echo"$(date)"# Useless use of echocat file| grep foo# Useless use of cat
ShellCheck can recognize issues related to data and typing:
args="$@"# Assigning arrays to stringsfiles=(foo bar);echo"$files"# Referencing arrays as stringsdeclare -A arr=(foo bar)# Associative arrays without indexprintf"%s\n""Arguments:$@."# Concatenating strings and arrays[[$#> 2 ]]# Comparing numbers as stringsvar=World;echo"Hello" var# Unused lowercase variablesecho"Hello$name"# Unassigned lowercase variablescmd|read bar;echo$bar# Assignments in subshellscat foo| cp bar# Piping to commands that don't readprintf'%s: %s\n' foo# Mismatches in printf argument counteval"${array[@]}"# Lost word boundaries in array evalforiin"${x[@]}";do${x[$i]}# Using array value as key
ShellCheck can make suggestions for improving the robustness of a script:
rm -rf"$STEAMROOT/"*# Catastrophic rmtouch ./-l; ls*# Globs that could become optionsfind. -exec sh -c'a && b {}'\;# Find -exec shell injectionprintf"Hello$name"# Variables in printf formatforfin$(ls*.txt);do# Iterating over ls outputexport MYVAR=$(cmd)# Masked exit codescase$versionin 2.*):;; 2.6.*)# Shadowed case branches
ShellCheck will warn when using features not supported by the shebang. For example, if you set the shebang to#!/bin/sh, ShellCheck will warn about portability issues similar tocheckbashisms:
echo {1..$n}# Works in ksh, but not bash/dash/shecho {1..10}# Works in ksh and bash, but not dash/shecho -n 42# Works in ksh, bash and dash, undefined in shexpr match str regex# Unportable alias for `expr str : regex`trap'exit 42' sigint# Unportable signal speccmd&> file# Unportable redirection operatorread foo< /dev/tcp/host/22# Unportable intercepted filesfoo-bar() { ..; }# Undefined/unsupported function name[$UID= 0 ]# Variable undefined in dash/shlocal var=value# local is undefined in shtime sleep 1| sleep 5# Undefined uses of 'time'
ShellCheck recognizes a menagerie of other issues:
PS1='\e[0;32m\$\e[0m'# PS1 colors not in \[..\]PATH="$PATH:~/bin"# Literal tilde in $PATHrm “file”# Unicode quotesecho"Hello world"# Carriage return / DOS line endingsecho hello\# Trailing spaces after \var=42echo$var# Expansion of inlined environment!# bin/bash -x -e # Common shebang errorsecho$((n/180*100))# Unnecessary loss of precisionls*[:digit:].txt# Bad character class globssed's/foo/bar/' file> file# Redirecting to inputvar2=$var2# Variable assigned to itself[ x$var= xval ]# Antiquated x-comparisonsls() { ls -l"$@"; }# Infinitely recursive wrapperalias ls='ls -l'; ls foo# Alias used before it takes effectfor x;dofor x;do# Nested loop uses same variablewhilegetopts"a" f;docase$fin"b")# Unhandled getopts flags
At first you're like "shellcheck is awesome" but then you're like "wtf are we still using bash"
Alexander Tarasikov,via Twitter
Issues can be ignored via environmental variable, command line, individually or globally within a file:
https://github.com/koalaman/shellcheck/wiki/Ignore
Please use the GitHub issue tracker for any bugs or feature suggestions:
https://github.com/koalaman/shellcheck/issues
Please submit patches to code or documentation as GitHub pull requests! Checkout theDevGuide on theShellCheck Wiki.
Contributions must be licensed under the GNU GPLv3.The contributor retains the copyright.
ShellCheck is licensed under the GNU General Public License, v3. A copy of this license is included in the fileLICENSE.
Copyright 2012-2019,Vidar 'koala_man' Holen and contributors.
Happy ShellChecking!
- The wiki haslong form descriptions for each warning, e.g.SC2221.
- ShellCheck does not attempt to enforce any kind of formatting or indenting style, so also check outshfmt!
About
ShellCheck, a static analysis tool for shell scripts
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.


