• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..03-May-2022-

_cabal_deps/H03-May-2022-157,80898,620

src/ShellCheck/H03-May-2022-14,97912,299

test/H09-Sep-2001-3330

CHANGELOG.mdH A D09-Sep-200119.5 KiB482401

LICENSEH A D09-Sep-200134.6 KiB685559

README.mdH A D09-Sep-200119.7 KiB552381

ShellCheck.cabalH A D03-May-20223.2 KiB132126

cabal.projectH A D03-May-20221.4 KiB4039

manpageH A D09-Sep-2001189 53

shellcheck.1.mdH A D09-Sep-200112.6 KiB385262

shellcheck.hsH A D09-Sep-200119.7 KiB591501

striptestsH A D09-Sep-20011.4 KiB7959

README.md

1[![Build Status](https://github.com/koalaman/shellcheck/actions/workflows/build.yml/badge.svg)](https://github.com/koalaman/shellcheck/actions/workflows/build.yml)
2
3
4# ShellCheck - A shell script static analysis tool
5
6ShellCheck is a GPLv3 tool that gives warnings and suggestions for bash/sh shell scripts:
7
8![Screenshot of a terminal showing problematic shell script lines highlighted](doc/terminal.png)
9
10The goals of ShellCheck are
11
12* To point out and clarify typical beginner's syntax issues that cause a shell
13  to give cryptic error messages.
14
15* To point out and clarify typical intermediate level semantic problems that
16  cause a shell to behave strangely and counter-intuitively.
17
18* To point out subtle caveats, corner cases and pitfalls that may cause an
19  advanced user's otherwise working script to fail under future circumstances.
20
21See [the gallery of bad code](README.md#user-content-gallery-of-bad-code) for examples of what ShellCheck can help you identify!
22
23## Table of Contents
24
25* [How to use](#how-to-use)
26  * [On the web](#on-the-web)
27  * [From your terminal](#from-your-terminal)
28  * [In your editor](#in-your-editor)
29  * [In your build or test suites](#in-your-build-or-test-suites)
30* [Installing](#installing)
31* [Compiling from source](#compiling-from-source)
32  * [Installing Cabal](#installing-cabal)
33  * [Compiling ShellCheck](#compiling-shellcheck)
34  * [Running tests](#running-tests)
35* [Gallery of bad code](#gallery-of-bad-code)
36  * [Quoting](#quoting)
37  * [Conditionals](#conditionals)
38  * [Frequently misused commands](#frequently-misused-commands)
39  * [Common beginner's mistakes](#common-beginners-mistakes)
40  * [Style](#style)
41  * [Data and typing errors](#data-and-typing-errors)
42  * [Robustness](#robustness)
43  * [Portability](#portability)
44  * [Miscellaneous](#miscellaneous)
45* [Testimonials](#testimonials)
46* [Ignoring issues](#ignoring-issues)
47* [Reporting bugs](#reporting-bugs)
48* [Contributing](#contributing)
49* [Copyright](#copyright)
50* [Other Resources](#other-resources)
51
52## How to use
53
54There are a number of ways to use ShellCheck!
55
56### On the web
57
58Paste a shell script on <https://www.shellcheck.net> for instant feedback.
59
60[ShellCheck.net](https://www.shellcheck.net) is always synchronized to the latest git commit, and is the easiest way to give ShellCheck a go. Tell your friends!
61
62### From your terminal
63
64Run `shellcheck yourscript` in your terminal for instant output, as seen above.
65
66### In your editor
67
68You can see ShellCheck suggestions directly in a variety of editors.
69
70* Vim, through [ALE](https://github.com/w0rp/ale), [Neomake](https://github.com/neomake/neomake), or [Syntastic](https://github.com/scrooloose/syntastic):
71
72![Screenshot of Vim showing inlined shellcheck feedback](doc/vim-syntastic.png).
73
74* Emacs, through [Flycheck](https://github.com/flycheck/flycheck) or [Flymake](https://github.com/federicotdn/flymake-shellcheck):
75
76![Screenshot of emacs showing inlined shellcheck feedback](doc/emacs-flycheck.png).
77
78* Sublime, through [SublimeLinter](https://github.com/SublimeLinter/SublimeLinter-shellcheck).
79
80* Atom, through [Linter](https://github.com/AtomLinter/linter-shellcheck).
81
82* VSCode, through [vscode-shellcheck](https://github.com/timonwong/vscode-shellcheck).
83
84* Most other editors, through [GCC error compatibility](shellcheck.1.md#user-content-formats).
85
86### In your build or test suites
87
88While ShellCheck is mostly intended for interactive use, it can easily be added to builds or test suites.
89It makes canonical use of exit codes, so you can just add a `shellcheck` command as part of the process.
90
91For example, in a Makefile:
92
93```Makefile
94check-scripts:
95    # Fail if any of these files have warnings
96    shellcheck myscripts/*.sh
97```
98
99or in a Travis CI `.travis.yml` file:
100
101```yaml
102script:
103  # Fail if any of these files have warnings
104  - shellcheck myscripts/*.sh
105```
106
107Services and platforms that have ShellCheck pre-installed and ready to use:
108
109* [Travis CI](https://travis-ci.org/)
110* [Codacy](https://www.codacy.com/)
111* [Code Climate](https://codeclimate.com/)
112* [Code Factor](https://www.codefactor.io/)
113* [CircleCI](https://circleci.com) via the [ShellCheck Orb](https://circleci.com/orbs/registry/orb/circleci/shellcheck)
114* [Github](https://github.com/features/actions) (only Linux)
115
116Most other services, including [GitLab](https://about.gitlab.com/), let you install
117ShellCheck yourself, either through the system's package manager (see [Installing](#installing)),
118or by downloading and unpacking a [binary release](#installing-a-pre-compiled-binary).
119
120It's a good idea to manually install a specific ShellCheck version regardless. This avoids
121any surprise build breaks when a new version with new warnings is published.
122
123For customized filtering or reporting, ShellCheck can output simple JSON, CheckStyle compatible XML,
124GCC compatible warnings as well as human readable text (with or without ANSI colors). See the
125[Integration](https://github.com/koalaman/shellcheck/wiki/Integration) wiki page for more documentation.
126
127## Installing
128
129The easiest way to install ShellCheck locally is through your package manager.
130
131On systems with Cabal (installs to `~/.cabal/bin`):
132
133    cabal update
134    cabal install ShellCheck
135
136On systems with Stack (installs to `~/.local/bin`):
137
138    stack update
139    stack install ShellCheck
140
141On Debian based distros:
142
143    sudo apt install shellcheck
144
145On Arch Linux based distros:
146
147    pacman -S shellcheck
148
149or get the dependency free [shellcheck-bin](https://aur.archlinux.org/packages/shellcheck-bin/) from the AUR.
150
151On Gentoo based distros:
152
153    emerge --ask shellcheck
154
155On EPEL based distros:
156
157    sudo yum -y install epel-release
158    sudo yum install ShellCheck
159
160On Fedora based distros:
161
162    dnf install ShellCheck
163
164On FreeBSD:
165
166    pkg install hs-ShellCheck
167
168On macOS (OS X) with Homebrew:
169
170    brew install shellcheck
171
172Or with MacPorts:
173
174    sudo port install shellcheck
175
176On OpenBSD:
177
178    pkg_add shellcheck
179
180On openSUSE
181
182    zypper in ShellCheck
183
184Or use OneClickInstall - <https://software.opensuse.org/package/ShellCheck>
185
186On Solus:
187
188    eopkg install shellcheck
189
190On Windows (via [chocolatey](https://chocolatey.org/packages/shellcheck)):
191
192```cmd
193C:\> choco install shellcheck
194```
195
196Or Windows (via [scoop](http://scoop.sh)):
197
198```cmd
199C:\> scoop install shellcheck
200```
201
202From [conda-forge](https://anaconda.org/conda-forge/shellcheck):
203
204    conda install -c conda-forge shellcheck
205
206From Snap Store:
207
208    snap install --channel=edge shellcheck
209
210From Docker Hub:
211
212```sh
213docker run --rm -v "$PWD:/mnt" koalaman/shellcheck:stable myscript
214# Or :v0.4.7 for that version, or :latest for daily builds
215```
216
217or use `koalaman/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.
218
219Using the [nix package manager](https://nixos.org/nix):
220```sh
221nix-env -iA nixpkgs.shellcheck
222```
223
224Alternatively, you can download pre-compiled binaries for the latest release here:
225
226* [Linux, x86_64](https://github.com/koalaman/shellcheck/releases/download/stable/shellcheck-stable.linux.x86_64.tar.xz) (statically linked)
227* [Linux, armv6hf](https://github.com/koalaman/shellcheck/releases/download/stable/shellcheck-stable.linux.armv6hf.tar.xz), i.e. Raspberry Pi (statically linked)
228* [Linux, aarch64](https://github.com/koalaman/shellcheck/releases/download/stable/shellcheck-stable.linux.aarch64.tar.xz) aka ARM64 (statically linked)
229* [macOS, x86_64](https://github.com/koalaman/shellcheck/releases/download/stable/shellcheck-stable.darwin.x86_64.tar.xz)
230* [Windows, x86](https://github.com/koalaman/shellcheck/releases/download/stable/shellcheck-stable.zip)
231
232or see the [GitHub Releases](https://github.com/koalaman/shellcheck/releases) for other releases
233(including the [latest](https://github.com/koalaman/shellcheck/releases/tag/latest) meta-release for daily git builds).
234
235Distro packages already come with a `man` page. If you are building from source, it can be installed with:
236
237```console
238pandoc -s -f markdown-smart -t man shellcheck.1.md -o shellcheck.1
239sudo mv shellcheck.1 /usr/share/man/man1
240```
241
242### pre-commit
243
244To run ShellCheck via [pre-commit](https://pre-commit.com/), add the hook to your `.pre-commit-config.yaml`:
245
246```
247repos:
248-   repo: https://github.com/koalaman/shellcheck-precommit
249    rev: v0.7.2
250    hooks:
251    -   id: shellcheck
252#       args: ["--severity=warning"]  # Optionally only show errors and warnings
253```
254
255### Travis CI
256
257Travis CI has now integrated ShellCheck by default, so you don't need to manually install it.
258
259If you still want to do so in order to upgrade at your leisure or ensure you're
260using the latest release, follow the steps below to install a binary version.
261
262### Installing a pre-compiled binary
263
264The pre-compiled binaries come in `tar.xz` files. To decompress them, make sure
265`xz` is installed.
266On Debian/Ubuntu/Mint, you can `apt install xz-utils`.
267On Redhat/Fedora/CentOS, `yum -y install xz`.
268
269A simple installer may do something like:
270
271```bash
272scversion="stable" # or "v0.4.7", or "latest"
273wget -qO- "https://github.com/koalaman/shellcheck/releases/download/${scversion?}/shellcheck-${scversion?}.linux.x86_64.tar.xz" | tar -xJv
274cp "shellcheck-${scversion}/shellcheck" /usr/bin/
275shellcheck --version
276```
277
278## Compiling from source
279
280This section describes how to build ShellCheck from a source directory. ShellCheck is written in Haskell and requires 2GB of RAM to compile.
281
282### Installing Cabal
283
284ShellCheck is built and packaged using Cabal. Install the package `cabal-install` from your system's package manager (with e.g. `apt-get`, `brew`, `emerge`, `yum`, or `zypper`).
285
286On 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.
287
288    $ brew install cabal-install
289
290On MacPorts, the package is instead called `hs-cabal-install`, while native Windows users should install the latest version of the Haskell platform from <https://www.haskell.org/platform/>
291
292Verify that `cabal` is installed and update its dependency list with
293
294    $ cabal update
295
296### Compiling ShellCheck
297
298`git clone` this repository, and `cd` to the ShellCheck source directory to build/install:
299
300    $ cabal install
301
302Or if you intend to run the tests:
303
304    $ cabal install --enable-tests
305
306This will compile ShellCheck and install it to your `~/.cabal/bin` directory.
307
308Add this directory to your `PATH` (for bash, add this to your `~/.bashrc`):
309
310```sh
311export PATH="$HOME/.cabal/bin:$PATH"
312```
313
314Log out and in again, and verify that your PATH is set up correctly:
315
316```sh
317$ which shellcheck
318~/.cabal/bin/shellcheck
319```
320
321On native Windows, the `PATH` should already be set up, but the system
322may use a legacy codepage. In `cmd.exe`, `powershell.exe` and Powershell ISE,
323make sure to use a TrueType font, not a Raster font, and set the active
324codepage to UTF-8 (65001) with `chcp`:
325
326```cmd
327chcp 65001
328```
329
330In Powershell ISE, you may need to additionally update the output encoding:
331
332```powershell
333[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
334```
335
336### Running tests
337
338To run the unit test suite:
339
340    $ cabal test
341
342## Gallery of bad code
343
344So what kind of things does ShellCheck look for? Here is an incomplete list of detected issues.
345
346### Quoting
347
348ShellCheck can recognize several types of incorrect quoting:
349
350```sh
351echo $1                           # Unquoted variables
352find . -name *.ogg                # Unquoted find/grep patterns
353rm "~/my file.txt"                # Quoted tilde expansion
354v='--verbose="true"'; cmd $v      # Literal quotes in variables
355for f in "*.ogg"                  # Incorrectly quoted 'for' loops
356touch $@                          # Unquoted $@
357echo 'Don't forget to restart!'   # Singlequote closed by apostrophe
358echo 'Don\'t try this at home'    # Attempting to escape ' in ''
359echo 'Path is $PATH'              # Variables in single quotes
360trap "echo Took ${SECONDS}s" 0    # Prematurely expanded trap
361unset var[i]                      # Array index treated as glob
362```
363
364### Conditionals
365
366ShellCheck can recognize many types of incorrect test statements.
367
368```sh
369[[ n != 0 ]]                      # Constant test expressions
370[[ -e *.mpg ]]                    # Existence checks of globs
371[[ $foo==0 ]]                     # Always true due to missing spaces
372[[ -n "$foo " ]]                  # Always true due to literals
373[[ $foo =~ "fo+" ]]               # Quoted regex in =~
374[ foo =~ re ]                     # Unsupported [ ] operators
375[ $1 -eq "shellcheck" ]           # Numerical comparison of strings
376[ $n && $m ]                      # && in [ .. ]
377[ grep -q foo file ]              # Command without $(..)
378[[ "$$file" == *.jpg ]]           # Comparisons that can't succeed
379(( 1 -lt 2 ))                     # Using test operators in ((..))
380[ x ] & [ y ] | [ z ]             # Accidental backgrounding and piping
381```
382
383### Frequently misused commands
384
385ShellCheck can recognize instances where commands are used incorrectly:
386
387```sh
388grep '*foo*' file                 # Globs in regex contexts
389find . -exec foo {} && bar {} \;  # Prematurely terminated find -exec
390sudo echo 'Var=42' > /etc/profile # Redirecting sudo
391time --format=%s sleep 10         # Passing time(1) flags to time builtin
392while read h; do ssh "$h" uptime  # Commands eating while loop input
393alias archive='mv $1 /backup'     # Defining aliases with arguments
394tr -cd '[a-zA-Z0-9]'              # [] around ranges in tr
395exec foo; echo "Done!"            # Misused 'exec'
396find -name \*.bak -o -name \*~ -delete  # Implicit precedence in find
397# find . -exec foo > bar \;       # Redirections in find
398f() { whoami; }; sudo f           # External use of internal functions
399```
400
401### Common beginner's mistakes
402
403ShellCheck recognizes many common beginner's syntax errors:
404
405```sh
406var = 42                          # Spaces around = in assignments
407$foo=42                           # $ in assignments
408for $var in *; do ...             # $ in for loop variables
409var$n="Hello"                     # Wrong indirect assignment
410echo ${var$n}                     # Wrong indirect reference
411var=(1, 2, 3)                     # Comma separated arrays
412array=( [index] = value )         # Incorrect index initialization
413echo $var[14]                     # Missing {} in array references
414echo "Argument 10 is $10"         # Positional parameter misreference
415if $(myfunction); then ..; fi     # Wrapping commands in $()
416else if othercondition; then ..   # Using 'else if'
417f; f() { echo "hello world; }     # Using function before definition
418[ false ]                         # 'false' being true
419if ( -f file )                    # Using (..) instead of test
420```
421
422### Style
423
424ShellCheck can make suggestions to improve style:
425
426```sh
427[[ -z $(find /tmp | grep mpg) ]]  # Use grep -q instead
428a >> log; b >> log; c >> log      # Use a redirection block instead
429echo "The time is `date`"         # Use $() instead
430cd dir; process *; cd ..;         # Use subshells instead
431echo $[1+2]                       # Use standard $((..)) instead of old $[]
432echo $(($RANDOM % 6))             # Don't use $ on variables in $((..))
433echo "$(date)"                    # Useless use of echo
434cat file | grep foo               # Useless use of cat
435```
436
437### Data and typing errors
438
439ShellCheck can recognize issues related to data and typing:
440
441```sh
442args="$@"                         # Assigning arrays to strings
443files=(foo bar); echo "$files"    # Referencing arrays as strings
444declare -A arr=(foo bar)          # Associative arrays without index
445printf "%s\n" "Arguments: $@."    # Concatenating strings and arrays
446[[ $# > 2 ]]                      # Comparing numbers as strings
447var=World; echo "Hello " var      # Unused lowercase variables
448echo "Hello $name"                # Unassigned lowercase variables
449cmd | read bar; echo $bar         # Assignments in subshells
450cat foo | cp bar                  # Piping to commands that don't read
451printf '%s: %s\n' foo             # Mismatches in printf argument count
452eval "${array[@]}"                # Lost word boundaries in array eval
453for i in "${x[@]}"; do ${x[$i]}   # Using array value as key
454```
455
456### Robustness
457
458ShellCheck can make suggestions for improving the robustness of a script:
459
460```sh
461rm -rf "$STEAMROOT/"*            # Catastrophic rm
462touch ./-l; ls *                 # Globs that could become options
463find . -exec sh -c 'a && b {}' \; # Find -exec shell injection
464printf "Hello $name"             # Variables in printf format
465for f in $(ls *.txt); do         # Iterating over ls output
466export MYVAR=$(cmd)              # Masked exit codes
467case $version in 2.*) :;; 2.6.*) # Shadowed case branches
468```
469
470### Portability
471
472ShellCheck 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 to `checkbashisms`:
473
474```sh
475echo {1..$n}                     # Works in ksh, but not bash/dash/sh
476echo {1..10}                     # Works in ksh and bash, but not dash/sh
477echo -n 42                       # Works in ksh, bash and dash, undefined in sh
478expr match str regex             # Unportable alias for `expr str : regex`
479trap 'exit 42' sigint            # Unportable signal spec
480cmd &> file                      # Unportable redirection operator
481read foo < /dev/tcp/host/22      # Unportable intercepted files
482foo-bar() { ..; }                # Undefined/unsupported function name
483[ $UID = 0 ]                     # Variable undefined in dash/sh
484local var=value                  # local is undefined in sh
485time sleep 1 | sleep 5           # Undefined uses of 'time'
486```
487
488### Miscellaneous
489
490ShellCheck recognizes a menagerie of other issues:
491
492```sh
493PS1='\e[0;32m\$\e[0m '            # PS1 colors not in \[..\]
494PATH="$PATH:~/bin"                # Literal tilde in $PATH
495rm “file”                         # Unicode quotes
496echo "Hello world"                # Carriage return / DOS line endings
497echo hello \                      # Trailing spaces after \
498var=42 echo $var                  # Expansion of inlined environment
499!# bin/bash -x -e                 # Common shebang errors
500echo $((n/180*100))               # Unnecessary loss of precision
501ls *[:digit:].txt                 # Bad character class globs
502sed 's/foo/bar/' file > file      # Redirecting to input
503var2=$var2                        # Variable assigned to itself
504[ x$var = xval ]                  # Antiquated x-comparisons
505ls() { ls -l "$@"; }              # Infinitely recursive wrapper
506alias ls='ls -l'; ls foo          # Alias used before it takes effect
507for x; do for x; do               # Nested loop uses same variable
508while getopts "a" f; do case $f in "b") # Unhandled getopts flags
509```
510
511## Testimonials
512
513> At first you're like "shellcheck is awesome" but then you're like "wtf are we still using bash"
514
515Alexander Tarasikov,
516[via Twitter](https://twitter.com/astarasikov/status/568825996532707330)
517
518## Ignoring issues
519
520Issues can be ignored via environmental variable, command line, individually or globally within a file:
521
522<https://github.com/koalaman/shellcheck/wiki/Ignore>
523
524## Reporting bugs
525
526Please use the GitHub issue tracker for any bugs or feature suggestions:
527
528<https://github.com/koalaman/shellcheck/issues>
529
530## Contributing
531
532Please submit patches to code or documentation as GitHub pull requests! Check
533out the [DevGuide](https://github.com/koalaman/shellcheck/wiki/DevGuide) on the
534ShellCheck Wiki.
535
536Contributions must be licensed under the GNU GPLv3.
537The contributor retains the copyright.
538
539## Copyright
540
541ShellCheck is licensed under the GNU General Public License, v3. A copy of this license is included in the file [LICENSE](LICENSE).
542
543Copyright 2012-2019, [Vidar 'koala_man' Holen](https://github.com/koalaman/) and contributors.
544
545Happy ShellChecking!
546
547## Other Resources
548
549* The wiki has [long form descriptions](https://github.com/koalaman/shellcheck/wiki/Checks) for each warning, e.g. [SC2221](https://github.com/koalaman/shellcheck/wiki/SC2221).
550* ShellCheck does not attempt to enforce any kind of formatting or indenting style, so also check out [shfmt](https://github.com/mvdan/sh)!
551
552