ShellCheck 0.9.0 → 0.12.0
raw patch · 29 files changed
Files
- CHANGELOG.md +97/−0
- README.md +27/−10
- ShellCheck.cabal +42/−22
- shellcheck-dev.hs +52/−0
- shellcheck.1.md +97/−19
- shellcheck.hs +262/−45
- src/ShellCheck/AST.hs +15/−7
- src/ShellCheck/ASTLib.hs +64/−38
- src/ShellCheck/Analytics.hs +5509/−5010
- src/ShellCheck/AnalyzerLib.hs +156/−86
- src/ShellCheck/CFG.hs +150/−121
- src/ShellCheck/CFGAnalysis.hs +40/−24
- src/ShellCheck/Checker.hs +246/−11
- src/ShellCheck/Checks/Commands.hs +330/−96
- src/ShellCheck/Checks/ControlFlow.hs +1/−1
- src/ShellCheck/Checks/Custom.hs +1/−1
- src/ShellCheck/Checks/ShellSupport.hs +216/−46
- src/ShellCheck/Data.hs +65/−32
- src/ShellCheck/Debug.hs +3/−2
- src/ShellCheck/EditorConfig.hs +468/−0
- src/ShellCheck/Formatter/CheckStyle.hs +4/−4
- src/ShellCheck/Formatter/Diff.hs +8/−2
- src/ShellCheck/Formatter/GCC.hs +5/−5
- src/ShellCheck/Formatter/JSON1.hs +5/−5
- src/ShellCheck/Formatter/TTY.hs +8/−8
- src/ShellCheck/Interface.hs +32/−10
- src/ShellCheck/Parser.hs +246/−102
- striptests +2/−2
- test/shellcheck.hs +22/−17
CHANGELOG.md view
@@ -1,3 +1,100 @@+## v0.12.0 - 2026-12-02+### Added+- Add `--files-from` option to read input files from a file+- Add `--extended-analysis=local` directive/flag to run dataflow analysis+ on the current script only, without considering any `source`d includes.+- `--list-optional` now lists the SC error code for optional checks+- Support EditorConfig `shellcheck.*` keys+- SC2336: Suggest `cp -R` over implementation specific `cp -r`+- SC2337: Warn about `grep -q` in pipelines under pipefail+- SC2338: Optionally suggest `[[ x == y ]]` over `[[ x = y ]]`+ (bash `require-double-equals`)+- SC2339/SC2340/SC2341/SC3426: Improved exit/return validation across shells++### Changed+- SC2024/SC2232: sudo redirection/builtin now also apply to doas and run0+- SC2114/SC2115: Unintentional `rm` warning now also triggers on globs like+ `rm /bin/*$empty*` and non-canonical paths like `rm -rf /home/foo/$empty/..`+- SC2236/SC2237: warning for negated -n/-z in `[ ]` now also triggers for `test`+- SC2312: `cmd || echo ..` is now considered handling failure+- SC3040: Support `pipefail` as specified in POSIX.1-2024++### Fixed+- `|&` now parses correctly as coprocess separator it Ksh+- Malformed shebangs retain warnings, but are no longer counted as shebangs+- `json1` output no longer contains duplicates instances of warnings+- SC1072 about an invalid `disable=` value now names the value instead+ of a missing `=`+- SC2031: No longer warns that assignments to `_` may be lost in a subshell+- SC2034: Unused variables no longer warn when `allexport` is enabled+- SC2035: Unprotected globs no longer warn when `noglob` is enabled+- SC2064: readonly variables no longer warn about expanding in `trap`+- SC2147: Check for tilde in $PATH now also triggers for declare/local/export+- SC2164: Status of `cd` is considered handled when returned from a function+- SC2178: Overwriting built-in bash arrays no longer warns in non-bash shells+- SC2185: `find -files0-from` no longer triggers check about missing path+- SC2218: Won't trigger on `bats` tests invoking functions defined later+- SC2317: No longer reports commands as unreachable when a `case` catch-all+ is followed by `;;&` and a non-default final clause+- SC3001: busybox sh now considered to support `<(process substitution)`++### Removed+- SC3003: removed since ANSI C string is specified in POSIX.1-2024+++## v0.11.0 - 2025-08-03+### Added+- SC2327/SC2328: Warn about capturing the output of redirected commands.+- SC2329: Warn when (non-escaping) functions are never invoked.+- SC2330: Warn about unsupported glob matches with [[ .. ]] in BusyBox.+- SC2331: Suggest using standard -e instead of unary -a in tests.+- SC2332: Warn about `[ ! -o opt ]` being unconditionally true in Bash.+- SC3062: Warn about bashism `[ -o opt ]`.+- Optional `avoid-negated-conditions`: suggest replacing `[ ! a -eq b ]`+ with `[ a -ne b ]`, and similar for -ge/-lt/=/!=/etc (SC2335).+- Precompiled binaries for Linux riscv64 (linux.riscv64)++### Changed+- SC2002 about Useless Use Of Cat is now disabled by default. It can be+ re-enabled with `--enable=useless-use-of-cat` or equivalent directive.+- SC2236/SC2237 about replacing `[ ! -n .. ]` with `[ -z ]` and vice versa+ is now optional under `avoid-negated-conditions`.+- SC2015 about `A && B || C` no longer triggers when B is a test command.+- SC3012: Do not warn about `\<` and `\>` in test/[] as specified in POSIX.1-2024+- Diff output now uses / as path separator on Windows++### Fixed+- SC2218 about function use-before-define is now more accurate.+- SC2317 about unreachable commands is now less spammy for nested ones.+- SC2292, optional suggestion for [[ ]], now triggers for Busybox.+- Updates for Bash 5.3, including `${| cmd; }` and `source -p`++### Removed+- SC3013: removed since the operators `-ot/-nt/-ef` are specified in POSIX.1-2024+++## v0.10.0 - 2024-03-07+### Added+- Precompiled binaries for macOS ARM64 (darwin.aarch64)+- Added support for busybox sh+- Added flag --rcfile to specify an rc file by name.+- Added `extended-analysis=true` directive to enable/disable dataflow analysis+ (with a corresponding --extended-analysis flag).+- SC2324: Warn when x+=1 appends instead of increments+- SC2325: Warn about multiple `!`s in dash/sh.+- SC2326: Warn about `foo | ! bar` in bash/dash/sh.+- SC3012: Warn about lexicographic-compare bashism in test like in [ ]+- SC3013: Warn bashism `test _ -op/-nt/-ef _` like in [ ]+- SC3014: Warn bashism `test _ == _` like in [ ]+- SC3015: Warn bashism `test _ =~ _` like in [ ]+- SC3016: Warn bashism `test -v _` like in [ ]+- SC3017: Warn bashism `test -a _` like in [ ]++### Fixed+- source statements with here docs now work correctly+- "(Array.!): undefined array element" error should no longer occur++ ## v0.9.0 - 2022-12-12 ### Added - SC2316: Warn about 'local readonly foo' and similar (thanks, patrickxia!)
README.md view
@@ -77,7 +77,7 @@ * Sublime, through [SublimeLinter](https://github.com/SublimeLinter/SublimeLinter-shellcheck). -* Atom, through [Linter](https://github.com/AtomLinter/linter-shellcheck).+* Pulsar Edit (former Atom), through [linter-shellcheck-pulsar](https://github.com/pulsar-cooperative/linter-shellcheck-pulsar). * VSCode, through [vscode-shellcheck](https://github.com/timonwong/vscode-shellcheck). @@ -110,8 +110,11 @@ * [Codacy](https://www.codacy.com/) * [Code Climate](https://codeclimate.com/) * [Code Factor](https://www.codefactor.io/)+* [Codety](https://www.codety.io/) via the [Codety Scanner](https://github.com/codetyio/codety-scanner) * [CircleCI](https://circleci.com) via the [ShellCheck Orb](https://circleci.com/orbs/registry/orb/circleci/shellcheck) * [Github](https://github.com/features/actions) (only Linux)+* [Trunk Code Quality](https://trunk.io/code-quality) (universal linter; [allows you to explicitly version your shellcheck install](https://github.com/trunk-io/plugins/blob/bcbb361dcdbe4619af51ea7db474d7fb87540d20/.trunk/trunk.yaml#L32)) via the [shellcheck plugin](https://github.com/trunk-io/plugins/blob/main/linters/shellcheck/plugin.yaml)+* [CodeRabbit](https://coderabbit.ai/) Most other services, including [GitLab](https://about.gitlab.com/), let you install ShellCheck yourself, either through the system's package manager (see [Installing](#installing)),@@ -193,6 +196,12 @@ C:\> choco install shellcheck ``` +Or Windows (via [winget](https://github.com/microsoft/winget-pkgs)):++```cmd+C:\> winget install --id koalaman.shellcheck+```+ Or Windows (via [scoop](http://scoop.sh)): ```cmd@@ -216,16 +225,28 @@ or 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. +Using [mise](https://mise.jdx.dev):+```sh+mise use shellcheck+```+ Using the [nix package manager](https://nixos.org/nix): ```sh nix-env -iA nixpkgs.shellcheck ``` +Using the [Flox package manager](https://flox.dev/)+```sh+flox install shellcheck+```+ Alternatively, you can download pre-compiled binaries for the latest release here: * [Linux, x86_64](https://github.com/koalaman/shellcheck/releases/download/stable/shellcheck-stable.linux.x86_64.tar.xz) (statically linked) * [Linux, armv6hf](https://github.com/koalaman/shellcheck/releases/download/stable/shellcheck-stable.linux.armv6hf.tar.xz), i.e. Raspberry Pi (statically linked) * [Linux, aarch64](https://github.com/koalaman/shellcheck/releases/download/stable/shellcheck-stable.linux.aarch64.tar.xz) aka ARM64 (statically linked)+* [Linux, riscv64](https://github.com/koalaman/shellcheck/releases/download/stable/shellcheck-stable.linux.riscv64.tar.xz) (statically linked)+* [macOS, aarch64](https://github.com/koalaman/shellcheck/releases/download/stable/shellcheck-stable.darwin.aarch64.tar.xz) * [macOS, x86_64](https://github.com/koalaman/shellcheck/releases/download/stable/shellcheck-stable.darwin.x86_64.tar.xz) * [Windows, x86](https://github.com/koalaman/shellcheck/releases/download/stable/shellcheck-stable.zip) @@ -246,7 +267,7 @@ ``` repos: - repo: https://github.com/koalaman/shellcheck-precommit- rev: v0.7.2+ rev: v0.11.0 hooks: - id: shellcheck # args: ["--severity=warning"] # Optionally only show errors and warnings@@ -299,10 +320,6 @@ $ cabal install -Or if you intend to run the tests:-- $ cabal install --enable-tests- This will compile ShellCheck and install it to your `~/.cabal/bin` directory. Add this directory to your `PATH` (for bash, add this to your `~/.bashrc`):@@ -392,7 +409,7 @@ while read h; do ssh "$h" uptime # Commands eating while loop input alias archive='mv $1 /backup' # Defining aliases with arguments tr -cd '[a-zA-Z0-9]' # [] around ranges in tr-exec foo; echo "Done!" # Misused 'exec'+exec foo; bar # Misused 'exec' find -name \*.bak -o -name \*~ -delete # Implicit precedence in find # find . -exec foo > bar \; # Redirections in find f() { whoami; }; sudo f # External use of internal functions@@ -431,7 +448,7 @@ echo $[1+2] # Use standard $((..)) instead of old $[] echo $(($RANDOM % 6)) # Don't use $ on variables in $((..)) echo "$(date)" # Useless use of echo-cat file | grep foo # Useless use of cat+cat file | grep foo # Useless use of cat (optional check) ``` ### Data and typing errors@@ -504,7 +521,8 @@ [ x$var = xval ] # Antiquated x-comparisons ls() { ls -l "$@"; } # Infinitely recursive wrapper alias ls='ls -l'; ls foo # Alias used before it takes effect-for x; do for x; do # Nested loop uses same variable+for x; do for x; do # Nested loop uses same variable name+set -o pipefail; cmd | grep -q x # pipefail interferes with grep -q while getopts "a" f; do case $f in "b") # Unhandled getopts flags ``` @@ -548,4 +566,3 @@ * 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). * ShellCheck does not attempt to enforce any kind of formatting or indenting style, so also check out [shfmt](https://github.com/mvdan/sh)!-
ShellCheck.cabal view
@@ -1,5 +1,5 @@ Name: ShellCheck-Version: 0.9.0+Version: 0.12.0 Synopsis: Shell script analysis tool License: GPL-3 License-file: LICENSE@@ -22,6 +22,8 @@ * To point out subtle caveats, corner cases and pitfalls, that may cause an advanced user's otherwise working script to fail under future circumstances. +tested-with: GHC == 8.0, GHC == 8.10, GHC == 9.0.1, GHC == 9.4.7, GHC == 9.6.6+ Extra-Doc-Files: README.md CHANGELOG.md@@ -37,8 +39,12 @@ source-repository head type: git- location: git://github.com/koalaman/shellcheck.git+ location: https://github.com/koalaman/shellcheck.git +flag dev-mode+ manual: True+ default: False+ library hs-source-dirs: src if impl(ghc < 8.0)@@ -46,27 +52,24 @@ semigroups build-depends: -- The lower bounds are based on GHC 7.10.3- -- The upper bounds are based on GHC 9.4.3- aeson >= 1.4.0 && < 2.2,+ -- The upper bounds are based on GHC 9.14.1+ aeson >= 1.4.0 && < 2.4, array >= 0.5.1 && < 0.6, base >= 4.8.0.0 && < 5,- bytestring >= 0.10.6 && < 0.12,- containers >= 0.5.6 && < 0.7,- deepseq >= 1.4.1 && < 1.5,- Diff >= 0.4.0 && < 0.5,- fgl >= 5.7.0 && < 5.9,- filepath >= 1.4.0 && < 1.5,- mtl >= 2.2.2 && < 2.3,+ bytestring >= 0.10.6 && < 0.13,+ containers >= 0.5.6 && < 0.9,+ deepseq >= 1.4.2 && < 1.6,+ Diff >= 0.4.0 && < 2.1,+ fgl >= 5.8.1.1 && < 5.9,+ filepath >= 1.4.0 && < 1.6,+ mtl >= 2.2.2 && < 2.4, parsec >= 3.1.14 && < 3.2,- QuickCheck >= 2.14.2 && < 2.15,+ QuickCheck >= 2.14.2 && < 2.20, regex-tdfa >= 1.2.0 && < 1.4,- transformers >= 0.4.2 && < 0.6,-- -- getXdgDirectory from 1.2.3.0- directory >= 1.2.3 && < 1.4,+ transformers >= 0.4.2 && < 0.7, - -- When cabal supports it, move this to setup-depends:- process+ -- pathIsSymbolicLink from 1.3.0.0+ directory >= 1.3 && < 1.4 exposed-modules: ShellCheck.AST ShellCheck.ASTLib@@ -81,7 +84,7 @@ ShellCheck.Checks.Custom ShellCheck.Checks.ShellSupport ShellCheck.Data- ShellCheck.Debug+ ShellCheck.EditorConfig ShellCheck.Fixer ShellCheck.Formatter.Format ShellCheck.Formatter.CheckStyle@@ -95,9 +98,14 @@ ShellCheck.Parser ShellCheck.Prelude ShellCheck.Regex++ if flag(dev-mode)+ exposed-modules:+ ShellCheck.Debug+ other-modules: Paths_ShellCheck- default-language: Haskell98+ default-language: Haskell2010 executable shellcheck if impl(ghc < 8.0)@@ -120,9 +128,21 @@ regex-tdfa, transformers, ShellCheck- default-language: Haskell98+ default-language: Haskell2010 main-is: shellcheck.hs +executable shellcheck-dev+ if flag(dev-mode)+ buildable: True+ else+ buildable: False+ build-depends:+ base,+ containers,+ ShellCheck+ default-language: Haskell2010+ main-is: shellcheck-dev.hs+ test-suite test-shellcheck type: exitcode-stdio-1.0 build-depends:@@ -142,5 +162,5 @@ regex-tdfa, transformers, ShellCheck- default-language: Haskell98+ default-language: Haskell2010 main-is: test/shellcheck.hs
+ shellcheck-dev.hs view
@@ -0,0 +1,52 @@+{-+ Copyright 2026 Vidar Holen++ This file is part of ShellCheck.+ https://www.shellcheck.net++ ShellCheck is free software: you can redistribute it and/or modify+ it under the terms of the GNU General Public License as published by+ the Free Software Foundation, either version 3 of the License, or+ (at your option) any later version.++ ShellCheck is distributed in the hope that it will be useful,+ but WITHOUT ANY WARRANTY; without even the implied warranty of+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ GNU General Public License for more details.++ You should have received a copy of the GNU General Public License+ along with this program. If not, see <https://www.gnu.org/licenses/>.+-}++-- shellcheck-dev is primarily meant for the potential benefits of AI.+-- It can be run with `cabal run -fdev-mode shellcheck-dev -- ast 'myshellcommand'`++import ShellCheck.Debug+import System.Environment+import System.Exit+import System.IO+import Data.List+import qualified Data.Map as Map++commands :: Map.Map String (String -> String)+commands = Map.fromList [+ ("ast", show . stringToAst)+ ]++validCommands :: String+validCommands = intercalate ", " $ Map.keys commands++putStrLnErr = hPutStrLn stderr++main = do+ args <- getArgs+ case args of+ [cmd, arg] ->+ case Map.lookup cmd commands of+ Just f -> putStrLn $ f arg+ Nothing -> do+ putStrLnErr $ "Unknown command. Try one of: " ++ validCommands+ exitFailure+ _ -> do+ putStrLnErr $ "Usage: shellcheck-dev command argument, where command is: " ++ validCommands+ exitFailure
shellcheck.1.md view
@@ -6,7 +6,7 @@ # SYNOPSIS -**shellcheck** [*OPTIONS*...] *FILES*...+**shellcheck** [*OPTIONS*...] [--files-from=FILE] *FILES*... # DESCRIPTION @@ -39,9 +39,9 @@ **-C**[*WHEN*],\ **--color**[=*WHEN*] -: For TTY output, enable colors *always*, *never* or *auto*. The default- is *auto*. **--color** without an argument is equivalent to- **--color=always**.+: For **tty** and **diff** output, enable colors *always*, *never* or+ *auto*. The default is *auto*. **--color** without an argument is+ equivalent to **--color=always**. **-i**\ *CODE1*[,*CODE2*...],\ **--include=***CODE1*[,*CODE2*...] @@ -56,12 +56,28 @@ options are cumulative, but all the codes can be specified at once, comma-separated as a single argument. +**--extended-analysis=full/local/none**++: Enable/disable Dataflow Analysis to identify more issues (default full). If+ ShellCheck uses too much CPU/RAM when checking scripts with several+ thousand lines of code, extended analysis can be either limited or+ disabled with this flag or a corresponding directive.++ Use `full` for full analysis, `local` to ignore sourced files, or `none` to+ disable. For compatibility, `true` means `full` while `false` means `none`.++ This flag overrides directives and rc files.+ **-f** *FORMAT*, **--format=***FORMAT* : Specify the output format of shellcheck, which prints its results in the standard output. Subsequent **-f** options are ignored, see **FORMATS** below for more information. +**--help**++: Show a usage summary and exit.+ **--list-optional** : Output a list of known optional checks. These can be enabled with **-o**@@ -69,8 +85,15 @@ **--norc** -: Don't try to look for .shellcheckrc configuration files.+: Don't try to look for .shellcheckrc or .editorconfig configuration files.+ This also disables **--rcfile**. +**--rcfile** *RCFILE*++: Prefer the specified configuration file over searching for one+ in the default locations. The specified file is not read if+ **--norc** is also given.+ **-o**\ *NAME1*[,*NAME2*...],\ **--enable=***NAME1*[,*NAME2*...] : Enable optional checks. The special name *all* enables all of them.@@ -80,12 +103,13 @@ **-P**\ *SOURCEPATH*,\ **--source-path=***SOURCEPATH* : Specify paths to search for sourced files, separated by `:` on Unix and- `;` on Windows. This is equivalent to specifying `search-path`+ `;` on Windows. This is equivalent to specifying `source-path` directives. **-s**\ *shell*,\ **--shell=***shell* -: Specify Bourne shell dialect. Valid values are *sh*, *bash*, *dash* and *ksh*.+: Specify Bourne shell dialect. Valid values are *sh*, *bash*, *dash*, *ksh*,+ and *busybox*. The default is to deduce the shell from the file's `shell` directive, shebang, or `.bash/.bats/.dash/.ksh` extension, in that order. *sh* refers to POSIX `sh` (not the system's), and will warn of portability issues.@@ -103,7 +127,7 @@ **-W** *NUM*,\ **--wiki-link-count=NUM** : For TTY output, show *NUM* wiki links to more information about mentioned- warnings. Set to 0 to disable them entirely.+ warnings. The default is 3. Set to 0 to disable them entirely. **-x**,\ **--external-sources** @@ -119,7 +143,13 @@ : One or more script files to check, or "-" for standard input. +**--files-from** *FILE* +: Read a list of files to check from *FILE*. Each line should contain one+ file path. Lines starting with `#` or empty lines are ignored. Use `-` to+ read the list from standard input. This option is processed in addition to+ any files specified on the command line.+ # FORMATS **tty**@@ -134,7 +164,7 @@ For example, in Vim, `:set makeprg=shellcheck\ -f\ gcc\ %` will allow using `:make` to check the script, and `:cnext` to jump to the next error. - <file>:<line>:<column>: <type>: <message>+ <file>:<line>:<column>: <type>: <message> [SC####] **checkstyle** @@ -171,7 +201,6 @@ && echo -e 'Playlist $f contains a HQ file in mp3 format' done - **json1** : Json is a popular serialization format that is more suitable for web@@ -183,15 +212,23 @@ { "file": "filename", "line": lineNumber,+ "endLine": endLineNumber, "column": columnNumber,+ "endColumn": endColumnNumber, "level": "severitylevel", "code": errorCode,- "message": "warning message"+ "message": "warning message",+ "fix": fixOrNull }, ... ] } + Each comment covers the whole range it refers to, so `endLine` and+ `endColumn` are always present. `fix` is `null` unless an automatic+ fix is available, in which case it is an object with a `replacements`+ array.+ **json** : This is a legacy version of the **json1** format. It's a raw array of@@ -202,7 +239,6 @@ : Suppress all normal output. Exit with zero if no issues are found, otherwise exit with one. Stops processing after the first issue. - # DIRECTIVES ShellCheck directives can be specified as comments in the shell script.@@ -236,13 +272,26 @@ : Disables a comma separated list of error codes for the following command. The command can be a simple command like `echo foo`, or a compound command like a function definition, subshell block or loop. A range can be- be specified with a dash, e.g. `disable=SC3000-SC4000` to exclude 3xxx.+ specified with a dash, e.g. `disable=SC3000-SC4000` to exclude 3xxx.+ The end of the range is exclusive: this example covers SC3000 through+ SC3999, but not SC4000. All warnings can be disabled with `disable=all`. **enable** : Enable an optional check by name, as listed with **--list-optional**. Only file-wide `enable` directives are considered. +**extended-analysis**+: Set to full/local/none to control dataflow analysis. `full` (default)+ performs whole-program analysis; `local` performs it per file, treating+ sourced files as opaque boundaries; `none` disables it. Specifying+ `# shellcheck extended-analysis=none` in particularly large (2000+ line)+ auto-generated scripts will reduce ShellCheck's resource usage at the+ expense of certain checks. `local` bounds memory when many checked files+ source a shared tree of libraries, while keeping per-file dataflow checks.++ For compatibility, `true` and `false` means `full` and `none` respectively.+ **external-sources** : Set to `true` in `.shellcheckrc` to always allow ShellCheck to open arbitrary files from 'source' statements (the way most tools do).@@ -267,7 +316,7 @@ **shell** : Overrides the shell detected from the shebang. This is useful for files meant to be included (and thus lacking a shebang), or possibly- as a more targeted alternative to 'disable=SC2039'.+ as a more targeted alternative to 'disable=SC3000-SC4000'. # RC FILES @@ -298,17 +347,46 @@ disable=SC2236 If no `.shellcheckrc` is found in any of the parent directories, ShellCheck-will look in `~/.shellcheckrc` followed by the XDG config directory-(usually `~/.config/shellcheckrc`) on Unix, or `%APPDATA%/shellcheckrc` on-Windows. Only the first file found will be used.+checks the following additional paths and uses the first file found: ++ On Unix-like systems, checks for `~/.shellcheckrc` followed by+ `$XDG_CONFIG_HOME/shellcheckrc` (no leading dot). If `$XDG_CONFIG_HOME` is+ unset it defaults to `~/.config`.++ On Windows systems, checks for `%APPDATA%\shellcheckrc` followed by+ `%XDG_CONFIG_HOME%\shellcheckrc`. If `%XDG_CONFIG_HOME%` is unset it defaults+ to `%APPDATA%`, making this path equal to the previous path and a no-op.+ Note for Snap users: the Snap sandbox disallows access to hidden files. Use `shellcheckrc` without the dot instead. Note for Docker users: ShellCheck will only be able to look for files that are mounted in the container, so `~/.shellcheckrc` will not be read. +# EDITORCONFIG +Unless `--norc` is used, ShellCheck will also look for a file `.editorconfig`+in the script's directory and each parent directory. Any section whose glob+pattern matches the checked file will have its `shellcheck.*` keys read as+directives, with the `shellcheck.` prefix stripped. This uses the same+`key=value` syntax as `.shellcheckrc`.++For example:++ [*.{ebuild,eclass}]+ shellcheck.shell=bash+ shellcheck.disable=SC2034++ [{PKGBUILD,APKBUILD}]+ shellcheck.shell=bash+ shellcheck.disable=SC2034++If no matching directives are found in any `.editorconfig` in the parent+directories, ShellCheck will look in the global default+`$XDG_CONFIG_HOME/editorconfig.ini` (usually `~/.config/editorconfig.ini`).++Directives from `.shellcheckrc`/`shellcheckrc` and from `.editorconfig` are+both applied, with `.shellcheckrc` taking precedence in case of conflicts.+ # ENVIRONMENT VARIABLES The environment variable `SHELLCHECK_OPTS` can be set with default flags:@@ -378,10 +456,10 @@ # COPYRIGHT -Copyright 2012-2022, Vidar Holen and contributors.+Copyright 2012-2026, Vidar Holen and contributors. Licensed under the GNU General Public License version 3 or later, see https://gnu.org/licenses/gpl.html # SEE ALSO -sh(1) bash(1)+sh(1), bash(1), dash(1), ksh(1)
shellcheck.hs view
@@ -20,6 +20,7 @@ import qualified ShellCheck.Analyzer import ShellCheck.Checker import ShellCheck.Data+import ShellCheck.EditorConfig import ShellCheck.Interface import ShellCheck.Regex @@ -76,7 +77,8 @@ externalSources :: Bool, sourcePaths :: [FilePath], formatterOptions :: FormatterOptions,- minSeverity :: Severity+ minSeverity :: Severity,+ rcfile :: Maybe FilePath } defaultOptions = Options {@@ -86,7 +88,8 @@ formatterOptions = newFormatterOptions { foColorOption = ColorAuto },- minSeverity = StyleC+ minSeverity = StyleC,+ rcfile = Nothing } usageHeader = "Usage: shellcheck [OPTIONS...] FILES..."@@ -100,13 +103,18 @@ (ReqArg (Flag "include") "CODE1,CODE2..") "Consider only given types of warnings", Option "e" ["exclude"] (ReqArg (Flag "exclude") "CODE1,CODE2..") "Exclude types of warnings",+ Option "" ["extended-analysis"]+ (ReqArg (Flag "extended-analysis") "mode") "Perform dataflow analysis: true|local|false (default true; local treats sourced files as boundaries)", Option "f" ["format"] (ReqArg (Flag "format") "FORMAT") $ "Output format (" ++ formatList ++ ")", Option "" ["list-optional"] (NoArg $ Flag "list-optional" "true") "List checks disabled by default", Option "" ["norc"]- (NoArg $ Flag "norc" "true") "Don't look for .shellcheckrc files",+ (NoArg $ Flag "norc" "true") "Don't look for .shellcheckrc and .editorconfig files",+ Option "" ["rcfile"]+ (ReqArg (Flag "rcfile") "RCFILE")+ "Prefer the specified configuration file over searching for one", Option "o" ["enable"] (ReqArg (Flag "enable") "check1,check2..") "List of optional checks to enable (or 'all')",@@ -114,8 +122,8 @@ (ReqArg (Flag "source-path") "SOURCEPATHS") "Specify path when looking for sourced files (\"SCRIPTDIR\" for script's dir)", Option "s" ["shell"]- (ReqArg (Flag "shell") "SHELLNAME")- "Specify dialect (sh, bash, dash, ksh)",+ (ReqArg (Flag "shell") "SHELLNAME") $+ "Specify dialect (" ++ intercalate ", " supportedShellDialects ++ ")", Option "S" ["severity"] (ReqArg (Flag "severity") "SEVERITY") "Minimum severity of errors to consider (error, warning, info, style)",@@ -127,12 +135,28 @@ Option "x" ["external-sources"] (NoArg $ Flag "externals" "true") "Allow 'source' outside of FILES", Option "" ["help"]- (NoArg $ Flag "help" "true") "Show this usage summary and exit"+ (NoArg $ Flag "help" "true") "Show this usage summary and exit",+ Option "" ["files-from"]+ (ReqArg (Flag "files-from") "FILE")+ "Read input files from FILE (one per line, or '-' for stdin)" ] getUsageInfo = usageInfo usageHeader options printErr = lift . hPutStrLn stderr +trim :: String -> String+trim = f . f+ where f = reverse . dropWhile isSpace++parseFileListLines :: String -> [FilePath]+parseFileListLines contents =+ [ line+ | raw <- lines contents+ , let line = trim raw+ , not (null line)+ , not ("#" `isPrefixOf` line)+ ]+ parseArguments :: [String] -> ExceptT Status IO ([Flag], [FilePath]) parseArguments argv = case getOpt Permute options argv of@@ -201,21 +225,49 @@ process :: [Flag] -> [FilePath] -> ExceptT Status IO Status process flags files = do options <- foldM (flip parseOption) defaultOptions flags- verifyFiles files++ let filesFrom = getOptions flags "files-from"+ extra <- fmap concat $ mapM readFilesFrom filesFrom+ let allFiles = extra ++ files++ -- It shouldn't be an error to do --files-from=/dev/null+ when (null filesFrom) $+ verifyFiles allFiles+ let format = fromMaybe "tty" $ getOption flags "format" let formatters = formats $ formatterOptions options- formatter <-- case Map.lookup format formatters of- Nothing -> do- printErr $ "Unknown format " ++ format- printErr "Supported formats:"- mapM_ (printErr . write) $ Map.keys formatters- throwError SupportFailure- where write s = " " ++ s- Just f -> ExceptT $ fmap Right f- sys <- lift $ ioInterface options files- lift $ runFormatter sys formatter options files+ formatter <- case Map.lookup format formatters of+ Nothing -> do+ printErr $ "Unknown format " ++ format+ printErr "Supported formats:"+ mapM_ (printErr . (" " ++)) $ Map.keys formatters+ throwError SupportFailure+ Just f -> ExceptT $ fmap Right f + lift $ do+ rcReadFailed <- newIORef False+ sys <- ioInterface options allFiles (writeIORef rcReadFailed True)+ status <- runFormatter sys formatter options allFiles+ failed <- readIORef rcReadFailed+ return $ if failed then RuntimeException else status++ where+ readFilesFrom :: FilePath -> ExceptT Status IO [FilePath]+ readFilesFrom "-" = do+ contents <- lift getContents+ return (parseFileListLines contents)++ readFilesFrom path = do+ result <- liftIO (try (readFile path) :: IO (Either IOException String))+ case result of+ Left e -> do+ printErr $ "Could not read file list: " ++ path ++ ": " ++ show e+ throwError RuntimeException+ Right contents ->+ return (parseFileListLines contents)+++ runFormatter :: SystemInterface IO -> Formatter -> Options -> [FilePath] -> IO Status runFormatter sys format options files = do@@ -246,15 +298,24 @@ } result <- checkScript sys checkspec onResult format result sys+ -- A malformed EditorConfig (invalid 'root' or 'shellcheck.*'+ -- directive) means shellcheck cannot apply the requested+ -- configuration, so it fails rather than silently proceeding. return $- if null (crComments result)- then NoProblems- else SomeProblems+ if any editorConfigError (crComments result)+ then SupportFailure+ else if null (crComments result)+ then NoProblems+ else SomeProblems + editorConfigError pc =+ cCode (pcComment pc) == 1134 &&+ ".editorconfig" `isSuffixOf` posFile (pcStartPos pc)+ parseEnum name value list =- case filter ((== value) . fst) list of- [(name, value)] -> return value- [] -> do+ case lookup value list of+ Just value -> return value+ Nothing -> do printErr $ "Unknown value for --" ++ name ++ ". " ++ "Valid options are: " ++ (intercalate ", " $ map fst list) throwError SupportFailure@@ -278,6 +339,7 @@ case flag of Flag "shell" str -> fromMaybe (die $ "Unknown shell: " ++ str) $ do+ guard $ str `elem` supportedShellDialects shell <- shellForExecutable str return $ return options { checkSpec = (checkSpec options) {@@ -367,16 +429,40 @@ } } - Flag "enable" value ->- let cs = checkSpec options in return options {+ Flag "rcfile" str -> do+ return options {+ rcfile = Just str+ }++ Flag "enable" value -> do+ let checks = filter (not . null) $ split ',' value+ let supported = map cdName ShellCheck.Analyzer.optionalChecks+ let unknown = filter (\name -> name /= "all" && name `notElem` supported) checks+ unless (null unknown) $ do+ printErr $ "Unrecognized optional checks: " ++ intercalate ", " unknown+ printErr "Supported checks: see `shellcheck --list-optional` (or 'all')"+ throwError SupportFailure+ let cs = checkSpec options+ return options { checkSpec = cs {- csOptionalChecks = (csOptionalChecks cs) ++ split ',' value+ csOptionalChecks = (csOptionalChecks cs) ++ checks } } + Flag "extended-analysis" str -> do+ value <- parseExtendedAnalysis str+ return options {+ checkSpec = (checkSpec options) {+ csExtendedAnalysis = Just value+ }+ }+ -- This flag is handled specially in 'process' Flag "format" _ -> return options + -- This flag is handled specially in 'process'+ Flag "files-from" _ -> return options+ Flag str _ -> do printErr $ "Internal error for --" ++ str ++ ". Please file a bug :(" return options@@ -391,12 +477,33 @@ throwError SyntaxFailure return (Prelude.read num :: Integer) -ioInterface :: Options -> [FilePath] -> IO (SystemInterface IO)-ioInterface options files = do+ parseBool str = do+ case str of+ "true" -> return True+ "false" -> return False+ _ -> do+ printErr $ "Invalid boolean, expected true/false: " ++ str+ throwError SyntaxFailure++ parseExtendedAnalysis str =+ case str of+ -- Legacy values+ "true" -> return ExtendedAnalysisFull+ "false" -> return ExtendedAnalysisNone+ -- New values+ "full" -> return ExtendedAnalysisFull+ "local" -> return ExtendedAnalysisLocal+ "none" -> return ExtendedAnalysisNone+ _ -> do+ printErr $ "Invalid extended-analysis value, expected full/local/none (or historical true=full, false=none): " ++ str+ throwError SyntaxFailure++ioInterface :: Options -> [FilePath] -> IO () -> IO (SystemInterface IO)+ioInterface options files onRcReadFailure = do inputs <- mapM normalize files cache <- newIORef emptyCache configCache <- newIORef ("", Nothing)- return SystemInterface {+ return (newSystemInterface :: SystemInterface IO) { siReadFile = get cache inputs, siFindSource = findSourceFile inputs (sourcePaths options), siGetConfig = getConfig configCache@@ -441,28 +548,135 @@ fallback :: FilePath -> IOException -> IO FilePath fallback path _ = return path - -- Returns the name and contents of .shellcheckrc for the given file++ -- Returns the name and contents of .shellcheckrc for the given file,+ -- merged with any shellcheck.* directives found in applicable+ -- EditorConfig files. getConfig cache filename = do- path <- normalize filename- let dir = takeDirectory path- (previousPath, result) <- readIORef cache- if dir == previousPath- then return result- else do- paths <- getConfigPaths dir- result <- findConfig paths- writeIORef cache (dir, result)- return result+ rcResult <- getRcConfig cache filename+ ecResult <- getEditorConfig filename+ return $ mergeConfigs filename rcResult ecResult + mergeConfigs filename rcResult ecResult =+ case (rcResult, ecResult) of+ (Nothing, Nothing) -> Nothing+ (Just (rcPath, rc), Nothing) -> Just (rcPath, rc)+ (Nothing, Just (ecPath, ec)) -> Just (ecPath, ec)+ (Just (rcPath, rc), Just (ecPath, ec)) ->+ if isEditorConfigRejection ec+ then Just (ecPath, ec)+ else Just (rcPath, rc ++ "\n" ++ ec)++ isEditorConfigRejection ec =+ all (\l -> null (trim l) || l == "invalid editorconfig value") (lines ec)+++ getRcConfig cache filename =+ case rcfile options of+ Just file -> do+ -- We have a specified rcfile. Ignore normal rcfile resolution.+ (path, result) <- readIORef cache+ if path == "/"+ then return result+ else do+ result <- readConfig doesFileExist onRcReadFailure file+ when (isNothing result) $ do+ hPutStrLn stderr $ "Warning: unable to read --rcfile " ++ file+ onRcReadFailure+ writeIORef cache ("/", result)+ return result++ Nothing -> do+ path <- normalize filename+ let dir = takeDirectory path+ (previousPath, result) <- readIORef cache+ if dir == previousPath+ then return result+ else do+ paths <- getConfigPaths dir+ result <- findConfig paths+ writeIORef cache (dir, result)+ return result++ -- Look for .editorconfig files in the target file's directory and+ -- all its parents (as per the EditorConfig spec), plus the global+ -- ${XDG_CONFIG_HOME}/editorconfig.ini default. shellcheck.* keys in+ -- matching sections are turned into directives.+ getEditorConfig filename = do+ -- Resolve the directory (to find .editorconfig files) but keep+ -- the leaf filename as-is so that globs match the symlink name+ -- rather than the resolved target.+ let name = takeFileName filename+ dir <- normalize (takeDirectory filename)+ let path = dir </> name+ dirConfigs <- collectDirConfigs dir+ globalConfig <- readGlobalEditorConfig+ let allConfigs = dirConfigs ++ globalConfig+ contributions = concatMap (directivesFor path) allConfigs+ return $ case contributions of+ [] -> Nothing+ ((sourceFile, _):_) -> Just (sourceFile, concatMap snd contributions)+ where+ -- For each EditorConfig file: report any invalid 'root'+ -- declaration (which takes priority) as a rejected config blob,+ -- otherwise yield the matching shellcheck.* directives+ -- (invalid directives are reported by editorConfigDirectives as a+ -- rejected blob so the .shellcheckrc parser emits SC1134).+ directivesFor path (file, contents) =+ let relative = makeRelativeTo (takeDirectory file) path+ in case invalidRootLines contents of+ (badLine:_) ->+ [(file, replicate (badLine - 1) '\n' ++ "invalid editorconfig value\n")]+ [] ->+ case editorConfigDirectives contents relative of+ Nothing -> []+ Just blob -> [(file, blob)]++ makeRelativeTo dir path =+ case stripPrefix (addTrailingSlash dir) path of+ Just rest -> rest+ Nothing -> takeFileName path++ addTrailingSlash dir+ | null dir = dir+ | last dir == '/' = dir+ | otherwise = dir ++ "/"++ collectDirConfigs dir = do+ current <- readConfig doesFileExist (return ()) (dir </> ".editorconfig")+ let isRoot = maybe False (isEditorConfigRoot . snd) current+ next = takeDirectory dir+ rest <- if next /= dir && not isRoot+ then collectDirConfigs next+ else return []+ return $ maybeToList current ++ rest++ readGlobalEditorConfig = do+ path <- (getXdgDirectory XdgConfig "editorconfig.ini")+ `catch` ((const $ return "") :: IOException -> IO FilePath)+ if null path+ then return []+ else maybeToList <$> readConfig doesFileExist (return ()) path+ findConfig paths = case paths of (file:rest) -> do- contents <- readConfig file+ contents <- readConfig rcFileExists onRcReadFailure file if isJust contents then return contents else findConfig rest [] -> return Nothing + -- A dangling symlink is a configured path even though its target is absent.+ rcFileExists file = do+ exists <- doesFileExist file+ if exists+ then return True+ else do+ link <- pathIsSymbolicLink file `catch`+ ((const $ return False) :: IOException -> IO Bool)+ if link then not <$> doesDirectoryExist file else return False+ -- Get a list of candidate filenames. This includes .shellcheckrc -- in all parent directories, plus the user's home dir and xdg dir. -- The dot is optional for Windows and Snap users.@@ -479,8 +693,8 @@ xdg <- getXdgDirectory XdgConfig "shellcheckrc" return [home, xdg] - readConfig file = do- exists <- doesFileExist file+ readConfig fileExists onReadFailure file = do+ exists <- fileExists file if exists then do (contents, _) <- inputFile file `catch` handler file@@ -490,7 +704,8 @@ where handler :: FilePath -> IOException -> IO (String, Bool) handler file err = do- putStrLn $ file ++ ": " ++ show err+ hPutStrLn stderr $ file ++ ": " ++ show err+ onReadFailure return ("", True) andM a b arg = do@@ -586,6 +801,8 @@ list = sortOn cdName ShellCheck.Analyzer.optionalChecks f item = do putStrLn $ "name: " ++ cdName item+ putStrLn $ "id: " ++ intercalate ", " ["SC" ++ show n | n <- cdId item]+ putStrLn $ "wiki: " ++ intercalate ", " [ShellCheck.Formatter.TTY.wikiLink ++ "SC" ++ show n | n <- cdId item] putStrLn $ "desc: " ++ cdDescription item putStrLn $ "example: " ++ cdPositive item putStrLn $ "fix: " ++ cdNegative item
src/ShellCheck/AST.hs view
@@ -31,6 +31,7 @@ data Quoted = Quoted | Unquoted deriving (Show, Eq) data Dashed = Dashed | Undashed deriving (Show, Eq)+data Piped = Piped | Unpiped deriving (Show, Eq) data AssignmentMode = Assign | Append deriving (Show, Eq) newtype FunctionKeyword = FunctionKeyword Bool deriving (Show, Eq) newtype FunctionParentheses = FunctionParentheses Bool deriving (Show, Eq)@@ -64,6 +65,7 @@ | Inner_T_UnparsedIndex SourcePos String | Inner_T_Assignment AssignmentMode String [t] t | Inner_T_Backgrounded t+ | Inner_T_KshCoprocess t | Inner_T_Backticked [t] | Inner_T_Bang | Inner_T_Banged t@@ -72,7 +74,7 @@ | Inner_T_CLOBBER | Inner_T_Case | Inner_T_CaseExpression t [(CaseType, [t], [t])]- | Inner_T_Condition ConditionType t+ | Inner_T_Condition ConditionType ConditionType t | Inner_T_DGREAT | Inner_T_DLESS | Inner_T_DLESSDASH@@ -84,7 +86,7 @@ | Inner_T_DollarDoubleQuoted [t] | Inner_T_DollarExpansion [t] | Inner_T_DollarSingleQuoted String- | Inner_T_DollarBraceCommandExpansion [t]+ | Inner_T_DollarBraceCommandExpansion Piped [t] | Inner_T_Done | Inner_T_DoubleQuoted [t] | Inner_T_EOF@@ -138,7 +140,7 @@ | Inner_T_WhileExpression [t] [t] | Inner_T_Annotation [Annotation] t | Inner_T_Pipe String- | Inner_T_CoProc (Maybe String) t+ | Inner_T_CoProc (Maybe Token) t | Inner_T_CoProcBody t | Inner_T_Include t | Inner_T_SourceCommand t t@@ -152,7 +154,12 @@ | ShellOverride String | SourcePath String | ExternalSources Bool+ | ExtendedAnalysis ExtendedAnalysisAnnotation deriving (Show, Eq)++-- ShellCheck.Interface has an equivalent one used externally, but it would be a circular dependency+data ExtendedAnalysisAnnotation = EAANone | EAALocal | EAAFull deriving (Show, Eq)+ data ConditionType = DoubleBracket | SingleBracket deriving (Show, Eq) pattern T_AND_IF id = OuterToken id Inner_T_AND_IF@@ -205,12 +212,13 @@ pattern T_Arithmetic id c = OuterToken id (Inner_T_Arithmetic c) pattern T_Array id t = OuterToken id (Inner_T_Array t) pattern TA_Sequence id l = OuterToken id (Inner_TA_Sequence l)-pattern TA_Parentesis id t = OuterToken id (Inner_TA_Parenthesis t)+pattern TA_Parenthesis id t = OuterToken id (Inner_TA_Parenthesis t) pattern T_Assignment id mode var indices value = OuterToken id (Inner_T_Assignment mode var indices value) pattern TA_Trinary id t1 t2 t3 = OuterToken id (Inner_TA_Trinary t1 t2 t3) pattern TA_Unary id op t1 = OuterToken id (Inner_TA_Unary op t1) pattern TA_Variable id str t = OuterToken id (Inner_TA_Variable str t) pattern T_Backgrounded id l = OuterToken id (Inner_T_Backgrounded l)+pattern T_KshCoprocess id l = OuterToken id (Inner_T_KshCoprocess l) pattern T_Backticked id list = OuterToken id (Inner_T_Backticked list) pattern T_Banged id l = OuterToken id (Inner_T_Banged l) pattern T_BatsTest id name t = OuterToken id (Inner_T_BatsTest name t)@@ -221,13 +229,13 @@ pattern TC_Binary id typ op lhs rhs = OuterToken id (Inner_TC_Binary typ op lhs rhs) pattern TC_Group id typ token = OuterToken id (Inner_TC_Group typ token) pattern TC_Nullary id typ token = OuterToken id (Inner_TC_Nullary typ token)-pattern T_Condition id typ token = OuterToken id (Inner_T_Condition typ token)+pattern T_Condition id typ close token = OuterToken id (Inner_T_Condition typ close token) pattern T_CoProcBody id t = OuterToken id (Inner_T_CoProcBody t) pattern T_CoProc id var body = OuterToken id (Inner_T_CoProc var body) pattern TC_Or id typ str t1 t2 = OuterToken id (Inner_TC_Or typ str t1 t2) pattern TC_Unary id typ op token = OuterToken id (Inner_TC_Unary typ op token) pattern T_DollarArithmetic id c = OuterToken id (Inner_T_DollarArithmetic c)-pattern T_DollarBraceCommandExpansion id list = OuterToken id (Inner_T_DollarBraceCommandExpansion list)+pattern T_DollarBraceCommandExpansion id pipe list = OuterToken id (Inner_T_DollarBraceCommandExpansion pipe list) pattern T_DollarBraced id braced op = OuterToken id (Inner_T_DollarBraced braced op) pattern T_DollarBracket id c = OuterToken id (Inner_T_DollarBracket c) pattern T_DollarDoubleQuoted id list = OuterToken id (Inner_T_DollarDoubleQuoted list)@@ -258,7 +266,7 @@ pattern T_UntilExpression id c l = OuterToken id (Inner_T_UntilExpression c l) pattern T_WhileExpression id c l = OuterToken id (Inner_T_WhileExpression c l) -{-# COMPLETE T_AND_IF, T_Bang, T_Case, TC_Empty, T_CLOBBER, T_DGREAT, T_DLESS, T_DLESSDASH, T_Do, T_DollarSingleQuoted, T_Done, T_DSEMI, T_Elif, T_Else, T_EOF, T_Esac, T_Fi, T_For, T_Glob, T_GREATAND, T_Greater, T_If, T_In, T_Lbrace, T_Less, T_LESSAND, T_LESSGREAT, T_Literal, T_Lparen, T_NEWLINE, T_OR_IF, T_ParamSubSpecialChar, T_Pipe, T_Rbrace, T_Rparen, T_Select, T_Semi, T_SingleQuoted, T_Then, T_UnparsedIndex, T_Until, T_While, TA_Assignment, TA_Binary, TA_Expansion, T_AndIf, T_Annotation, T_Arithmetic, T_Array, TA_Sequence, TA_Parentesis, T_Assignment, TA_Trinary, TA_Unary, TA_Variable, T_Backgrounded, T_Backticked, T_Banged, T_BatsTest, T_BraceExpansion, T_BraceGroup, TC_And, T_CaseExpression, TC_Binary, TC_Group, TC_Nullary, T_Condition, T_CoProcBody, T_CoProc, TC_Or, TC_Unary, T_DollarArithmetic, T_DollarBraceCommandExpansion, T_DollarBraced, T_DollarBracket, T_DollarDoubleQuoted, T_DollarExpansion, T_DoubleQuoted, T_Extglob, T_FdRedirect, T_ForArithmetic, T_ForIn, T_Function, T_HereDoc, T_HereString, T_IfExpression, T_Include, T_IndexedElement, T_IoDuplicate, T_IoFile, T_NormalWord, T_OrIf, T_Pipeline, T_ProcSub, T_Redirecting, T_Script, T_SelectIn, T_SimpleCommand, T_SourceCommand, T_Subshell, T_UntilExpression, T_WhileExpression #-}+{-# COMPLETE T_AND_IF, T_Bang, T_Case, TC_Empty, T_CLOBBER, T_DGREAT, T_DLESS, T_DLESSDASH, T_Do, T_DollarSingleQuoted, T_Done, T_DSEMI, T_Elif, T_Else, T_EOF, T_Esac, T_Fi, T_For, T_Glob, T_GREATAND, T_Greater, T_If, T_In, T_Lbrace, T_Less, T_LESSAND, T_LESSGREAT, T_Literal, T_Lparen, T_NEWLINE, T_OR_IF, T_ParamSubSpecialChar, T_Pipe, T_Rbrace, T_Rparen, T_Select, T_Semi, T_SingleQuoted, T_Then, T_UnparsedIndex, T_Until, T_While, TA_Assignment, TA_Binary, TA_Expansion, T_AndIf, T_Annotation, T_Arithmetic, T_Array, TA_Sequence, TA_Parenthesis, T_Assignment, TA_Trinary, TA_Unary, TA_Variable, T_Backgrounded, T_Backticked, T_Banged, T_BatsTest, T_BraceExpansion, T_BraceGroup, TC_And, T_CaseExpression, TC_Binary, TC_Group, TC_Nullary, T_Condition, T_CoProcBody, T_CoProc, TC_Or, TC_Unary, T_DollarArithmetic, T_DollarBraceCommandExpansion, T_DollarBraced, T_DollarBracket, T_DollarDoubleQuoted, T_DollarExpansion, T_DoubleQuoted, T_Extglob, T_FdRedirect, T_ForArithmetic, T_ForIn, T_Function, T_HereDoc, T_HereString, T_IfExpression, T_Include, T_IndexedElement, T_IoDuplicate, T_IoFile, T_KshCoprocess, T_NormalWord, T_OrIf, T_Pipeline, T_ProcSub, T_Redirecting, T_Script, T_SelectIn, T_SimpleCommand, T_SourceCommand, T_Subshell, T_UntilExpression, T_WhileExpression #-} instance Eq Token where OuterToken _ a == OuterToken _ b = a == b
src/ShellCheck/ASTLib.hs view
@@ -31,8 +31,9 @@ import Data.Functor.Identity import Data.List import Data.Maybe+import qualified Data.List.NonEmpty as NE import qualified Data.Map as Map-import Numeric (showHex)+import Numeric (readHex, readOct, showHex) import Test.QuickCheck @@ -157,9 +158,10 @@ _ -> False -- Is this token a flag where the - is unquoted?-isUnquotedFlag token = fromMaybe False $ do- str <- getLeadingUnquotedString token- return $ "-" `isPrefixOf` str+isUnquotedFlag token =+ case getLeadingUnquotedString token of+ Just ('-':_) -> True+ _ -> False -- getGnuOpts "erd:u:" will parse a list of arguments tokens like `read` -- -re -d : -u 3 bar@@ -384,6 +386,16 @@ prop_getLiteralString11 = getLiteralString (T_DollarSingleQuoted (Id 0) "\\1") == Just "\1" prop_getLiteralString12 = getLiteralString (T_DollarSingleQuoted (Id 0) "\\12") == Just "\o12" prop_getLiteralString13 = getLiteralString (T_DollarSingleQuoted (Id 0) "\\123") == Just "\o123"+prop_getLiteralString14 = getLiteralString (T_DollarSingleQuoted (Id 0) "\\e[1mfoo\\E[0mbar") == Just "\ESC[1mfoo\ESC[0mbar"+prop_getLiteralString15 = getLiteralString (T_DollarSingleQuoted (Id 0) "\\?") == Just "?"+prop_getLiteralString16 = getLiteralString (T_DollarSingleQuoted (Id 0) "\\u9") == Just "\t"+prop_getLiteralString17 = getLiteralString (T_DollarSingleQuoted (Id 0) "\\u2F") == Just "/"+prop_getLiteralString18 = getLiteralString (T_DollarSingleQuoted (Id 0) "\\u100") == Just "Ā"+prop_getLiteralString19 = getLiteralString (T_DollarSingleQuoted (Id 0) "\\u1d00") == Just "ᴀ"+prop_getLiteralString20 = getLiteralString (T_DollarSingleQuoted (Id 0) "\\u1D56C") == Just "ᵖC"+prop_getLiteralString21 = getLiteralString (T_DollarSingleQuoted (Id 0) "\\U9z") == Just "\tz"+prop_getLiteralString22 = getLiteralString (T_DollarSingleQuoted (Id 0) "\\u1d00.") == Just "ᴀ."+prop_getLiteralString23 = getLiteralString (T_DollarSingleQuoted (Id 0) "\\U1D56C") == Just "𝕬" -- Maybe get the literal value of a token, using a custom function -- to map unrecognized Tokens into strings.@@ -407,43 +419,46 @@ 'a' -> '\a' : rest 'b' -> '\b' : rest 'e' -> '\x1B' : rest+ 'E' -> '\x1B' : rest 'f' -> '\f' : rest 'n' -> '\n' : rest 'r' -> '\r' : rest 't' -> '\t' : rest 'v' -> '\v' : rest+ '\\' -> '\\' : rest '\'' -> '\'' : rest '"' -> '"' : rest- '\\' -> '\\' : rest+ '?' -> '?' : rest 'x' ->- case cs of- (x:y:more) | isHexDigit x && isHexDigit y ->- chr (16*(digitToInt x) + (digitToInt y)) : decodeEscapes more- (x:more) | isHexDigit x ->- chr (digitToInt x) : decodeEscapes more- more -> '\\' : 'x' : decodeEscapes more- _ | isOctDigit c ->- let (digits, more) = spanMax isOctDigit 3 (c:cs)- num = (parseOct digits) `mod` 256- in (chr num) : decodeEscapes more- _ -> '\\' : c : rest+ case readHex (take 2 cs) of+ [(n, s)] -> chr n : s ++ decodeEscapes (drop 2 cs)+ _ -> '\\' : 'x' : rest+ 'u' ->+ case readHex (take 4 cs) of+ [(n, s)] -> chr n : s ++ decodeEscapes (drop 4 cs)+ _ -> '\\' : 'x' : rest+ 'U' ->+ case readHex (take 8 cs) of+ [(n, s)] -> chr n : s ++ decodeEscapes (drop 8 cs)+ _ -> '\\' : 'x' : rest+ _ ->+ case readOct (c:take 2 cs) of+ [(n, s)] -> chr (n `mod` 256) : s ++ decodeEscapes (drop 2 cs)+ _ -> '\\' : c : rest where rest = decodeEscapes cs- parseOct = f 0- where- f n "" = n- f n (c:rest) = f (n * 8 + digitToInt c) rest- spanMax f n list =- let (first, second) = span f list- (prefix, suffix) = splitAt n first- in- (prefix, suffix ++ second) decodeEscapes (c:cs) = c : decodeEscapes cs decodeEscapes [] = [] -- Is this token a string literal? isLiteral t = isJust $ getLiteralString t +-- Is this token a string literal number?+isLiteralNumber t = fromMaybe False $ do+ s <- getLiteralString t+ guard $ all isDigit s+ return True+ -- Escape user data for messages. -- Messages generally avoid repeating user data, but sometimes it's helpful. e4m = escapeForMessage@@ -553,7 +568,7 @@ case t of T_DollarExpansion _ [c] -> extract c T_Backticked _ [c] -> extract c- T_DollarBraceCommandExpansion _ [c] -> extract c+ T_DollarBraceCommandExpansion _ _ [c] -> extract c _ -> Nothing where extract (T_Pipeline _ _ [cmd]) = getCommandName cmd@@ -608,7 +623,7 @@ T_Annotation _ _ t -> getCommandSequences t T_DollarExpansion _ cmds -> [cmds]- T_DollarBraceCommandExpansion _ cmds -> [cmds]+ T_DollarBraceCommandExpansion _ _ cmds -> [cmds] T_Backticked _ cmds -> [cmds] _ -> [] @@ -758,8 +773,8 @@ prop_executableFromShebang7 = executableFromShebang "/usr/bin/env --split-string bash -x" == "bash" prop_executableFromShebang8 = executableFromShebang "/usr/bin/env --split-string foo=bar bash -x" == "bash" prop_executableFromShebang9 = executableFromShebang "/usr/bin/env foo=bar dash" == "dash"-prop_executableFromShebang10 = executableFromShebang "/bin/busybox sh" == "ash"-prop_executableFromShebang11 = executableFromShebang "/bin/busybox ash" == "ash"+prop_executableFromShebang10 = executableFromShebang "/bin/busybox sh" == "busybox sh"+prop_executableFromShebang11 = executableFromShebang "/bin/busybox ash" == "busybox ash" -- Get the shell executable from a string like '/usr/bin/env bash' executableFromShebang :: String -> String@@ -776,7 +791,8 @@ [x] -> basename x (first:second:args) | basename first == "busybox" -> case basename second of- "sh" -> "ash" -- busybox sh is ash+ "sh" -> "busybox sh"+ "ash" -> "busybox ash" x -> x (first:args) | basename first == "env" -> fromEnvArgs args@@ -856,8 +872,7 @@ -- Get the variables from indices like ["x", "y"] in ${var[x+y+1]} prop_getIndexReferences1 = getIndexReferences "var[x+y+1]" == ["x", "y"] getIndexReferences s = fromMaybe [] $ do- match <- matchRegex re s- index <- match !!! 0+ index:_ <- matchRegex re s return $ matchAllStrings variableNameRegex index where re = mkRegex "(\\[.*\\])"@@ -868,8 +883,7 @@ prop_getOffsetReferences4 = getOffsetReferences "[foo]:bar:baz" == ["bar", "baz"] getOffsetReferences mods = fromMaybe [] $ do -- if mods start with [, then drop until ]- match <- matchRegex re mods- offsets <- match !!! 1+ _:offsets:_ <- matchRegex re mods return $ matchAllStrings variableNameRegex offsets where re = mkRegex "^(\\[.+\\])? *:([^-=?+].*)"@@ -886,11 +900,17 @@ in getBracedReference str == str _ -> False +-- Return the referenced variable if (and only if) it's an unmodified parameter expansion.+getUnmodifiedParameterExpansion t =+ case t of+ T_DollarBraced _ _ list -> do+ let str = concat $ oversimplify list+ guard $ getBracedReference str == str+ return str+ _ -> Nothing+ --- A list of the element and all its parents up to the root node.-getPath tree t = t :- case Map.lookup (getId t) tree of- Nothing -> []- Just parent -> getPath tree parent+getPath tree = NE.unfoldr $ \t -> (t, Map.lookup (getId t) tree) isClosingFileOp op = case op of@@ -902,6 +922,12 @@ case root of T_Annotation _ list _ -> [s | EnableComment s <- list] _ -> []++getExtendedAnalysisDirective :: Token -> Maybe ExtendedAnalysisAnnotation+getExtendedAnalysisDirective root =+ case root of+ T_Annotation _ list _ -> listToMaybe $ [s | ExtendedAnalysis s <- list]+ _ -> Nothing return [] runTests = $quickCheckAll
src/ShellCheck/Analytics.hs view
@@ -1,5014 +1,5513 @@ {-- Copyright 2012-2022 Vidar Holen-- This file is part of ShellCheck.- https://www.shellcheck.net-- ShellCheck is free software: you can redistribute it and/or modify- it under the terms of the GNU General Public License as published by- the Free Software Foundation, either version 3 of the License, or- (at your option) any later version.-- ShellCheck is distributed in the hope that it will be useful,- but WITHOUT ANY WARRANTY; without even the implied warranty of- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the- GNU General Public License for more details.-- You should have received a copy of the GNU General Public License- along with this program. If not, see <https://www.gnu.org/licenses/>.--}-{-# LANGUAGE TemplateHaskell #-}-{-# LANGUAGE FlexibleContexts #-}-module ShellCheck.Analytics (checker, optionalChecks, ShellCheck.Analytics.runTests) where--import ShellCheck.AST-import ShellCheck.ASTLib-import ShellCheck.AnalyzerLib hiding (producesComments)-import ShellCheck.CFG-import qualified ShellCheck.CFGAnalysis as CF-import ShellCheck.Data-import ShellCheck.Parser-import ShellCheck.Prelude-import ShellCheck.Interface-import ShellCheck.Regex--import Control.Arrow (first)-import Control.Monad-import Control.Monad.Identity-import Control.Monad.State-import Control.Monad.Writer hiding ((<>))-import Control.Monad.Reader-import Data.Char-import Data.Functor-import Data.Function (on)-import Data.List-import Data.Maybe-import Data.Ord-import Data.Semigroup-import Debug.Trace -- STRIP-import qualified Data.Map.Strict as Map-import qualified Data.Set as S-import Test.QuickCheck.All (forAllProperties)-import Test.QuickCheck.Test (quickCheckWithResult, stdArgs, maxSuccess)---- Checks that are run on the AST root-treeChecks :: [Parameters -> Token -> [TokenComment]]-treeChecks = [- nodeChecksToTreeCheck nodeChecks- ,subshellAssignmentCheck- ,checkQuotesInLiterals- ,checkShebangParameters- ,checkFunctionsUsedExternally- ,checkUnusedAssignments- ,checkUnpassedInFunctions- ,checkArrayWithoutIndex- ,checkShebang- ,checkUnassignedReferences- ,checkUncheckedCdPushdPopd- ,checkArrayAssignmentIndices- ,checkUseBeforeDefinition- ,checkAliasUsedInSameParsingUnit- ,checkArrayValueUsedAsIndex- ]--checker spec params = mkChecker spec params treeChecks--mkChecker spec params checks =- Checker {- perScript = \(Root root) -> do- tell $ concatMap (\f -> f params root) all,- perToken = const $ return ()- }- where- all = checks ++ optionals- optionalKeys = asOptionalChecks spec- optionals =- if "all" `elem` optionalKeys- then map snd optionalTreeChecks- else mapMaybe (\c -> Map.lookup c optionalCheckMap) optionalKeys---checkList l t = concatMap (\f -> f t) l---- Checks that are run on each node in the AST-runNodeAnalysis f p t = execWriter (doAnalysis (f p) t)---- Perform multiple node checks in a single iteration over the tree-nodeChecksToTreeCheck checkList =- runNodeAnalysis- (\p t -> (mapM_ ((\ f -> f t) . (\ f -> f p))- checkList))--nodeChecks :: [Parameters -> Token -> Writer [TokenComment] ()]-nodeChecks = [- checkUuoc- ,checkPipePitfalls- ,checkForInQuoted- ,checkForInLs- ,checkShorthandIf- ,checkDollarStar- ,checkUnquotedDollarAt- ,checkStderrRedirect- ,checkUnquotedN- ,checkNumberComparisons- ,checkSingleBracketOperators- ,checkDoubleBracketOperators- ,checkLiteralBreakingTest- ,checkConstantNullary- ,checkDivBeforeMult- ,checkArithmeticDeref- ,checkArithmeticBadOctal- ,checkComparisonAgainstGlob- ,checkCaseAgainstGlob- ,checkCommarrays- ,checkOrNeq- ,checkEchoWc- ,checkConstantIfs- ,checkPipedAssignment- ,checkAssignAteCommand- ,checkUuoeVar- ,checkQuotedCondRegex- ,checkForInCat- ,checkFindExec- ,checkValidCondOps- ,checkGlobbedRegex- ,checkTestRedirects- ,checkBadParameterSubstitution- ,checkPS1Assignments- ,checkBackticks- ,checkInexplicablyUnquoted- ,checkTildeInQuotes- ,checkLonelyDotDash- ,checkSpuriousExec- ,checkSpuriousExpansion- ,checkDollarBrackets- ,checkSshHereDoc- ,checkGlobsAsOptions- ,checkWhileReadPitfalls- ,checkArithmeticOpCommand- ,checkCharRangeGlob- ,checkUnquotedExpansions- ,checkSingleQuotedVariables- ,checkRedirectToSame- ,checkPrefixAssignmentReference- ,checkLoopKeywordScope- ,checkCdAndBack- ,checkWrongArithmeticAssignment- ,checkConditionalAndOrs- ,checkFunctionDeclarations- ,checkStderrPipe- ,checkOverridingPath- ,checkArrayAsString- ,checkUnsupported- ,checkMultipleAppends- ,checkSuspiciousIFS- ,checkShouldUseGrepQ- ,checkTestArgumentSplitting- ,checkConcatenatedDollarAt- ,checkTildeInPath- ,checkReadWithoutR- ,checkLoopVariableReassignment- ,checkTrailingBracket- ,checkReturnAgainstZero- ,checkRedirectedNowhere- ,checkUnmatchableCases- ,checkSubshellAsTest- ,checkSplittingInArrays- ,checkRedirectionToNumber- ,checkGlobAsCommand- ,checkFlagAsCommand- ,checkEmptyCondition- ,checkPipeToNowhere- ,checkForLoopGlobVariables- ,checkSubshelledTests- ,checkInvertedStringTest- ,checkRedirectionToCommand- ,checkDollarQuoteParen- ,checkUselessBang- ,checkTranslatedStringVariable- ,checkModifiedArithmeticInRedirection- ,checkBlatantRecursion- ,checkBadTestAndOr- ,checkAssignToSelf- ,checkEqualsInCommand- ,checkSecondArgIsComparison- ,checkComparisonWithLeadingX- ,checkCommandWithTrailingSymbol- ,checkUnquotedParameterExpansionPattern- ,checkBatsTestDoesNotUseNegation- ,checkCommandIsUnreachable- ,checkSpacefulnessCfg- ,checkOverwrittenExitCode- ,checkUnnecessaryArithmeticExpansionIndex- ,checkUnnecessaryParens- ]--optionalChecks = map fst optionalTreeChecks---prop_verifyOptionalExamples = all check optionalTreeChecks- where- check (desc, check) =- verifyTree check (cdPositive desc)- && verifyNotTree check (cdNegative desc)--optionalTreeChecks :: [(CheckDescription, (Parameters -> Token -> [TokenComment]))]-optionalTreeChecks = [- (newCheckDescription {- cdName = "quote-safe-variables",- cdDescription = "Suggest quoting variables without metacharacters",- cdPositive = "var=hello; echo $var",- cdNegative = "var=hello; echo \"$var\""- }, nodeChecksToTreeCheck [checkVerboseSpacefulnessCfg])-- ,(newCheckDescription {- cdName = "avoid-nullary-conditions",- cdDescription = "Suggest explicitly using -n in `[ $var ]`",- cdPositive = "[ \"$var\" ]",- cdNegative = "[ -n \"$var\" ]"- }, nodeChecksToTreeCheck [checkNullaryExpansionTest])-- ,(newCheckDescription {- cdName = "add-default-case",- cdDescription = "Suggest adding a default case in `case` statements",- cdPositive = "case $? in 0) echo 'Success';; esac",- cdNegative = "case $? in 0) echo 'Success';; *) echo 'Fail' ;; esac"- }, nodeChecksToTreeCheck [checkDefaultCase])-- ,(newCheckDescription {- cdName = "require-variable-braces",- cdDescription = "Suggest putting braces around all variable references",- cdPositive = "var=hello; echo $var",- cdNegative = "var=hello; echo ${var}"- }, nodeChecksToTreeCheck [checkVariableBraces])-- ,(newCheckDescription {- cdName = "check-unassigned-uppercase",- cdDescription = "Warn when uppercase variables are unassigned",- cdPositive = "echo $VAR",- cdNegative = "VAR=hello; echo $VAR"- }, checkUnassignedReferences' True)-- ,(newCheckDescription {- cdName = "require-double-brackets",- cdDescription = "Require [[ and warn about [ in Bash/Ksh",- cdPositive = "[ -e /etc/issue ]",- cdNegative = "[[ -e /etc/issue ]]"- }, checkRequireDoubleBracket)-- ,(newCheckDescription {- cdName = "check-set-e-suppressed",- cdDescription = "Notify when set -e is suppressed during function invocation",- cdPositive = "set -e; func() { cp *.txt ~/backup; rm *.txt; }; func && echo ok",- cdNegative = "set -e; func() { cp *.txt ~/backup; rm *.txt; }; func; echo ok"- }, checkSetESuppressed)-- ,(newCheckDescription {- cdName = "check-extra-masked-returns",- cdDescription = "Check for additional cases where exit codes are masked",- cdPositive = "rm -r \"$(get_chroot_dir)/home\"",- cdNegative = "set -e; dir=\"$(get_chroot_dir)\"; rm -r \"$dir/home\""- }, checkExtraMaskedReturns)- ]--optionalCheckMap :: Map.Map String (Parameters -> Token -> [TokenComment])-optionalCheckMap = Map.fromList $ map item optionalTreeChecks- where- item (desc, check) = (cdName desc, check)--wouldHaveBeenGlob s = '*' `elem` s--verify :: (Parameters -> Token -> Writer [TokenComment] ()) -> String -> Bool-verify f s = checkNode f s == Just True--verifyNot :: (Parameters -> Token -> Writer [TokenComment] ()) -> String -> Bool-verifyNot f s = checkNode f s == Just False--verifyTree :: (Parameters -> Token -> [TokenComment]) -> String -> Bool-verifyTree f s = producesComments f s == Just True--verifyNotTree :: (Parameters -> Token -> [TokenComment]) -> String -> Bool-verifyNotTree f s = producesComments f s == Just False--checkCommand str f t@(T_SimpleCommand id _ (cmd:rest))- | t `isCommand` str = f cmd rest-checkCommand _ _ _ = return ()--checkUnqualifiedCommand str f t@(T_SimpleCommand id _ (cmd:rest))- | t `isUnqualifiedCommand` str = f cmd rest-checkUnqualifiedCommand _ _ _ = return ()--verifyCodes :: (Parameters -> Token -> Writer [TokenComment] ()) -> [Code] -> String -> Bool-verifyCodes f l s = codes == Just l- where- treeCheck = runNodeAnalysis f- comments = runAndGetComments treeCheck s- codes = map (cCode . tcComment) <$> comments--checkNode f = producesComments (runNodeAnalysis f)-producesComments :: (Parameters -> Token -> [TokenComment]) -> String -> Maybe Bool-producesComments f s = not . null <$> runAndGetComments f s--runAndGetComments f s = do- let pr = pScript s- root <- prRoot pr- let spec = defaultSpec pr- let params = makeParameters spec- return $- filterByAnnotation spec params $- f params root---- Copied from https://wiki.haskell.org/Edit_distance-dist :: Eq a => [a] -> [a] -> Int-dist a b- = last (if lab == 0 then mainDiag- else if lab > 0 then lowers !! (lab - 1)- else{- < 0 -} uppers !! (-1 - lab))- where mainDiag = oneDiag a b (head uppers) (-1 : head lowers)- uppers = eachDiag a b (mainDiag : uppers) -- upper diagonals- lowers = eachDiag b a (mainDiag : lowers) -- lower diagonals- eachDiag a [] diags = []- eachDiag a (bch:bs) (lastDiag:diags) = oneDiag a bs nextDiag lastDiag : eachDiag a bs diags- where nextDiag = head (tail diags)- oneDiag a b diagAbove diagBelow = thisdiag- where doDiag [] b nw n w = []- doDiag a [] nw n w = []- doDiag (ach:as) (bch:bs) nw n w = me : doDiag as bs me (tail n) (tail w)- where me = if ach == bch then nw else 1 + min3 (head w) nw (head n)- firstelt = 1 + head diagBelow- thisdiag = firstelt : doDiag a b firstelt diagAbove (tail diagBelow)- lab = length a - length b- min3 x y z = if x < y then x else min y z--hasFloatingPoint params = shellType params == Ksh---- Checks whether the current parent path is part of a condition-isCondition [] = False-isCondition [_] = False-isCondition (child:parent:rest) =- case child of- T_BatsTest {} -> True -- count anything in a @test as conditional- _ -> getId child `elem` map getId (getConditionChildren parent) || isCondition (parent:rest)- where- getConditionChildren t =- case t of- T_AndIf _ left right -> [left]- T_OrIf id left right -> [left]- T_IfExpression id conditions elses -> concatMap (take 1 . reverse . fst) conditions- T_WhileExpression id c l -> take 1 . reverse $ c- T_UntilExpression id c l -> take 1 . reverse $ c- _ -> []---- helpers to build replacements-replaceStart id params n r =- let tp = tokenPositions params- (start, _) = tp Map.! id- new_end = start {- posColumn = posColumn start + n- }- depth = length $ getPath (parentMap params) (T_EOF id)- in- newReplacement {- repStartPos = start,- repEndPos = new_end,- repString = r,- repPrecedence = depth,- repInsertionPoint = InsertAfter- }-replaceEnd id params n r =- let tp = tokenPositions params- (_, end) = tp Map.! id- new_start = end {- posColumn = posColumn end - n- }- new_end = end {- posColumn = posColumn end- }- depth = length $ getPath (parentMap params) (T_EOF id)- in- newReplacement {- repStartPos = new_start,- repEndPos = new_end,- repString = r,- repPrecedence = depth,- repInsertionPoint = InsertBefore- }-replaceToken id params r =- let tp = tokenPositions params- (start, end) = tp Map.! id- depth = length $ getPath (parentMap params) (T_EOF id)- in- newReplacement {- repStartPos = start,- repEndPos = end,- repString = r,- repPrecedence = depth,- repInsertionPoint = InsertBefore- }--surroundWith id params s = fixWith [replaceStart id params 0 s, replaceEnd id params 0 s]-fixWith fixes = newFix { fixReplacements = fixes }--analyse f t = execState (doAnalysis f t) []---- Make a map from functions to definition IDs-functions t = Map.fromList $ analyse findFunctions t-findFunctions (T_Function id _ _ name _)- = modify ((name, id):)-findFunctions _ = return ()---- Make a map from aliases to definition IDs-aliases t = Map.fromList $ analyse findAliases t-findAliases t@(T_SimpleCommand _ _ (_:args))- | t `isUnqualifiedCommand` "alias" = mapM_ getAlias args-findAliases _ = return ()-getAlias arg =- let string = onlyLiteralString arg- in when ('=' `elem` string) $- modify ((takeWhile (/= '=') string, getId arg):)--prop_checkEchoWc3 = verify checkEchoWc "n=$(echo $foo | wc -c)"-checkEchoWc _ (T_Pipeline id _ [a, b]) =- when (acmd == ["echo", "${VAR}"]) $- case bcmd of- ["wc", "-c"] -> countMsg- ["wc", "-m"] -> countMsg- _ -> return ()- where- acmd = oversimplify a- bcmd = oversimplify b- countMsg = style id 2000 "See if you can use ${#variable} instead."-checkEchoWc _ _ = return ()--prop_checkPipedAssignment1 = verify checkPipedAssignment "A=ls | grep foo"-prop_checkPipedAssignment2 = verifyNot checkPipedAssignment "A=foo cmd | grep foo"-prop_checkPipedAssignment3 = verifyNot checkPipedAssignment "A=foo"-checkPipedAssignment _ (T_Pipeline _ _ (T_Redirecting _ _ (T_SimpleCommand id (_:_) []):_:_)) =- warn id 2036 "If you wanted to assign the output of the pipeline, use a=$(b | c) ."-checkPipedAssignment _ _ = return ()--prop_checkAssignAteCommand1 = verify checkAssignAteCommand "A=ls -l"-prop_checkAssignAteCommand2 = verify checkAssignAteCommand "A=ls --sort=$foo"-prop_checkAssignAteCommand3 = verify checkAssignAteCommand "A=cat foo | grep bar"-prop_checkAssignAteCommand4 = verifyNot checkAssignAteCommand "A=foo ls -l"-prop_checkAssignAteCommand5 = verify checkAssignAteCommand "PAGER=cat grep bar"-prop_checkAssignAteCommand6 = verifyNot checkAssignAteCommand "PAGER=\"cat\" grep bar"-prop_checkAssignAteCommand7 = verify checkAssignAteCommand "here=pwd"-checkAssignAteCommand _ (T_SimpleCommand id [T_Assignment _ _ _ _ assignmentTerm] list) =- -- Check if first word is intended as an argument (flag or glob).- if firstWordIsArg list- then- err id 2037 "To assign the output of a command, use var=$(cmd) ."- else- -- Check if it's a known, unquoted command name.- when (isCommonCommand $ getUnquotedLiteral assignmentTerm) $- warn id 2209 "Use var=$(command) to assign output (or quote to assign string)."- where- isCommonCommand (Just s) = s `elem` commonCommands- isCommonCommand _ = False- firstWordIsArg list = fromMaybe False $ do- head <- list !!! 0- return $ isGlob head || isUnquotedFlag head--checkAssignAteCommand _ _ = return ()--prop_checkArithmeticOpCommand1 = verify checkArithmeticOpCommand "i=i + 1"-prop_checkArithmeticOpCommand2 = verify checkArithmeticOpCommand "foo=bar * 2"-prop_checkArithmeticOpCommand3 = verifyNot checkArithmeticOpCommand "foo + opts"-checkArithmeticOpCommand _ (T_SimpleCommand id [T_Assignment {}] (firstWord:_)) =- mapM_ check $ getGlobOrLiteralString firstWord- where- check op =- when (op `elem` ["+", "-", "*", "/"]) $- warn (getId firstWord) 2099 $- "Use $((..)) for arithmetics, e.g. i=$((i " ++ op ++ " 2))"-checkArithmeticOpCommand _ _ = return ()--prop_checkWrongArit = verify checkWrongArithmeticAssignment "i=i+1"-prop_checkWrongArit2 = verify checkWrongArithmeticAssignment "n=2; i=n*2"-checkWrongArithmeticAssignment params (T_SimpleCommand id [T_Assignment _ _ _ _ val] []) =- sequence_ $ do- str <- getNormalString val- match <- matchRegex regex str- var <- match !!! 0- op <- match !!! 1- Map.lookup var references- return . warn (getId val) 2100 $- "Use $((..)) for arithmetics, e.g. i=$((i " ++ op ++ " 2))"- where- regex = mkRegex "^([_a-zA-Z][_a-zA-Z0-9]*)([+*-]).+$"- references = foldl (flip ($)) Map.empty (map insertRef $ variableFlow params)- insertRef (Assignment (_, _, name, _)) =- Map.insert name ()- insertRef _ = Prelude.id-- getNormalString (T_NormalWord _ words) = do- parts <- mapM getLiterals words- return $ concat parts- getNormalString _ = Nothing-- getLiterals (T_Literal _ s) = return s- getLiterals (T_Glob _ s) = return s- getLiterals _ = Nothing-checkWrongArithmeticAssignment _ _ = return ()---prop_checkUuoc1 = verify checkUuoc "cat foo | grep bar"-prop_checkUuoc2 = verifyNot checkUuoc "cat * | grep bar"-prop_checkUuoc3 = verify checkUuoc "cat \"$var\" | grep bar"-prop_checkUuoc3b = verifyNot checkUuoc "cat $var | grep bar"-prop_checkUuoc3c = verifyNot checkUuoc "cat \"${!var}\" | grep bar"-prop_checkUuoc4 = verifyNot checkUuoc "cat $var"-prop_checkUuoc5 = verifyNot checkUuoc "cat \"$@\""-prop_checkUuoc6 = verifyNot checkUuoc "cat -n | grep bar"-checkUuoc _ (T_Pipeline _ _ (T_Redirecting _ _ cmd:_:_)) =- checkCommand "cat" (const f) cmd- where- f [word] | not (mayBecomeMultipleArgs word || isOption word) =- style (getId word) 2002 "Useless cat. Consider 'cmd < file | ..' or 'cmd file | ..' instead."- f _ = return ()- isOption word = "-" `isPrefixOf` onlyLiteralString word-checkUuoc _ _ = return ()--prop_checkPipePitfalls3 = verify checkPipePitfalls "ls | grep -v mp3"-prop_checkPipePitfalls4 = verifyNot checkPipePitfalls "find . -print0 | xargs -0 foo"-prop_checkPipePitfalls5 = verifyNot checkPipePitfalls "ls -N | foo"-prop_checkPipePitfalls6 = verify checkPipePitfalls "find . | xargs foo"-prop_checkPipePitfalls7 = verifyNot checkPipePitfalls "find . -printf '%s\\n' | xargs foo"-prop_checkPipePitfalls8 = verify checkPipePitfalls "foo | grep bar | wc -l"-prop_checkPipePitfalls9 = verifyNot checkPipePitfalls "foo | grep -o bar | wc -l"-prop_checkPipePitfalls10 = verifyNot checkPipePitfalls "foo | grep -o bar | wc"-prop_checkPipePitfalls11 = verifyNot checkPipePitfalls "foo | grep bar | wc"-prop_checkPipePitfalls12 = verifyNot checkPipePitfalls "foo | grep -o bar | wc -c"-prop_checkPipePitfalls13 = verifyNot checkPipePitfalls "foo | grep bar | wc -c"-prop_checkPipePitfalls14 = verifyNot checkPipePitfalls "foo | grep -o bar | wc -cmwL"-prop_checkPipePitfalls15 = verifyNot checkPipePitfalls "foo | grep bar | wc -cmwL"-prop_checkPipePitfalls16 = verifyNot checkPipePitfalls "foo | grep -r bar | wc -l"-prop_checkPipePitfalls17 = verifyNot checkPipePitfalls "foo | grep -l bar | wc -l"-prop_checkPipePitfalls18 = verifyNot checkPipePitfalls "foo | grep -L bar | wc -l"-prop_checkPipePitfalls19 = verifyNot checkPipePitfalls "foo | grep -A2 bar | wc -l"-prop_checkPipePitfalls20 = verifyNot checkPipePitfalls "foo | grep -B999 bar | wc -l"-prop_checkPipePitfalls21 = verifyNot checkPipePitfalls "foo | grep --after-context 999 bar | wc -l"-prop_checkPipePitfalls22 = verifyNot checkPipePitfalls "foo | grep -B 1 --after-context 999 bar | wc -l"-prop_checkPipePitfalls23 = verifyNot checkPipePitfalls "ps -o pid,args -p $(pgrep java) | grep -F net.shellcheck.Test"-checkPipePitfalls _ (T_Pipeline id _ commands) = do- for ["find", "xargs"] $- \(find:xargs:_) ->- let args = oversimplify xargs ++ oversimplify find- in- unless (any ($ args) [- hasShortParameter '0',- hasParameter "null",- hasParameter "print0",- hasParameter "printf"- ]) $ warn (getId find) 2038- "Use -print0/-0 or -exec + to allow for non-alphanumeric filenames."-- for ["ps", "grep"] $- \(ps:grep:_) ->- let- psFlags = maybe [] (map snd . getAllFlags) $ getCommand ps- in- -- There are many ways to specify a pid: 1, -1, p 1, wup 1, -q 1, -p 1, --pid 1.- -- For simplicity we only deal with the most canonical looking flags:- unless (any (`elem` ["p", "pid", "q", "quick-pid"]) psFlags) $- info (getId ps) 2009 "Consider using pgrep instead of grepping ps output."-- for ["grep", "wc"] $- \(grep:wc:_) ->- let flagsGrep = maybe [] (map snd . getAllFlags) $ getCommand grep- flagsWc = maybe [] (map snd . getAllFlags) $ getCommand wc- in- unless (any (`elem` ["l", "files-with-matches", "L", "files-without-matches", "o", "only-matching", "r", "R", "recursive", "A", "after-context", "B", "before-context"]) flagsGrep- || any (`elem` ["m", "chars", "w", "words", "c", "bytes", "L", "max-line-length"]) flagsWc- || null flagsWc) $- style (getId grep) 2126 "Consider using 'grep -c' instead of 'grep|wc -l'."-- didLs <- fmap or . sequence $ [- for' ["ls", "grep"] $- \x -> warn x 2010 "Don't use ls | grep. Use a glob or a for loop with a condition to allow non-alphanumeric filenames.",- for' ["ls", "xargs"] $- \x -> warn x 2011 "Use 'find .. -print0 | xargs -0 ..' or 'find .. -exec .. +' to allow non-alphanumeric filenames."- ]- unless didLs $ void $- for ["ls", "?"] $- \(ls:_) -> unless (hasShortParameter 'N' (oversimplify ls)) $- info (getId ls) 2012 "Use find instead of ls to better handle non-alphanumeric filenames."- where- for l f =- let indices = indexOfSublists l (map (headOrDefault "" . oversimplify) commands)- in do- mapM_ (f . (\ n -> take (length l) $ drop n commands)) indices- return . not . null $ indices- for' l f = for l (first f)- first func (x:_) = func (getId $ getCommandTokenOrThis x)- first _ _ = return ()- hasShortParameter char = any (\x -> "-" `isPrefixOf` x && char `elem` x)- hasParameter string =- any (isPrefixOf string . dropWhile (== '-'))-checkPipePitfalls _ _ = return ()--indexOfSublists sub = f 0- where- f _ [] = []- f n a@(r:rest) =- let others = f (n+1) rest in- if match sub a- then n:others- else others- match ("?":r1) (_:r2) = match r1 r2- match (x1:r1) (x2:r2) | x1 == x2 = match r1 r2- match [] _ = True- match _ _ = False---prop_checkShebangParameters1 = verifyTree checkShebangParameters "#!/usr/bin/env bash -x\necho cow"-prop_checkShebangParameters2 = verifyNotTree checkShebangParameters "#! /bin/sh -l "-prop_checkShebangParameters3 = verifyNotTree checkShebangParameters "#!/usr/bin/env -S bash -x\necho cow"-prop_checkShebangParameters4 = verifyNotTree checkShebangParameters "#!/usr/bin/env --split-string bash -x\necho cow"-checkShebangParameters p (T_Annotation _ _ t) = checkShebangParameters p t-checkShebangParameters _ (T_Script _ (T_Literal id sb) _) =- [makeComment ErrorC id 2096 "On most OS, shebangs can only specify a single parameter." | isMultiWord]- where- isMultiWord = length (words sb) > 2 && not (sb `matches` re)- re = mkRegex "env +(-S|--split-string)"--prop_checkShebang1 = verifyNotTree checkShebang "#!/usr/bin/env bash -x\necho cow"-prop_checkShebang2 = verifyNotTree checkShebang "#! /bin/sh -l "-prop_checkShebang3 = verifyTree checkShebang "ls -l"-prop_checkShebang4 = verifyNotTree checkShebang "#shellcheck shell=sh\nfoo"-prop_checkShebang5 = verifyTree checkShebang "#!/usr/bin/env ash"-prop_checkShebang6 = verifyNotTree checkShebang "#!/usr/bin/env ash\n# shellcheck shell=dash\n"-prop_checkShebang7 = verifyNotTree checkShebang "#!/usr/bin/env ash\n# shellcheck shell=sh\n"-prop_checkShebang8 = verifyTree checkShebang "#!bin/sh\ntrue"-prop_checkShebang9 = verifyNotTree checkShebang "# shellcheck shell=sh\ntrue"-prop_checkShebang10 = verifyNotTree checkShebang "#!foo\n# shellcheck shell=sh ignore=SC2239\ntrue"-prop_checkShebang11 = verifyTree checkShebang "#!/bin/sh/\ntrue"-prop_checkShebang12 = verifyTree checkShebang "#!/bin/sh/ -xe\ntrue"-prop_checkShebang13 = verifyTree checkShebang "#!/bin/busybox sh"-prop_checkShebang14 = verifyNotTree checkShebang "#!/bin/busybox sh\n# shellcheck shell=sh\n"-prop_checkShebang15 = verifyNotTree checkShebang "#!/bin/busybox sh\n# shellcheck shell=dash\n"-prop_checkShebang16 = verifyTree checkShebang "#!/bin/busybox ash"-prop_checkShebang17 = verifyNotTree checkShebang "#!/bin/busybox ash\n# shellcheck shell=dash\n"-prop_checkShebang18 = verifyNotTree checkShebang "#!/bin/busybox ash\n# shellcheck shell=sh\n"-checkShebang params (T_Annotation _ list t) =- if any isOverride list then [] else checkShebang params t- where- isOverride (ShellOverride _) = True- isOverride _ = False-checkShebang params (T_Script _ (T_Literal id sb) _) = execWriter $ do- unless (shellTypeSpecified params) $ do- when (null sb) $- err id 2148 "Tips depend on target shell and yours is unknown. Add a shebang or a 'shell' directive."- when (executableFromShebang sb == "ash") $- warn id 2187 "Ash scripts will be checked as Dash. Add '# shellcheck shell=dash' to silence."- unless (null sb) $ do- unless ("/" `isPrefixOf` sb) $- err id 2239 "Ensure the shebang uses an absolute path to the interpreter."- when ("/" `isSuffixOf` head (words sb)) $- err id 2246 "This shebang specifies a directory. Ensure the interpreter is a file."---prop_checkForInQuoted = verify checkForInQuoted "for f in \"$(ls)\"; do echo foo; done"-prop_checkForInQuoted2 = verifyNot checkForInQuoted "for f in \"$@\"; do echo foo; done"-prop_checkForInQuoted2a = verifyNot checkForInQuoted "for f in *.mp3; do echo foo; done"-prop_checkForInQuoted2b = verify checkForInQuoted "for f in \"*.mp3\"; do echo foo; done"-prop_checkForInQuoted3 = verify checkForInQuoted "for f in 'find /'; do true; done"-prop_checkForInQuoted4 = verify checkForInQuoted "for f in 1,2,3; do true; done"-prop_checkForInQuoted4a = verifyNot checkForInQuoted "for f in foo{1,2,3}; do true; done"-prop_checkForInQuoted5 = verify checkForInQuoted "for f in ls; do true; done"-prop_checkForInQuoted6 = verifyNot checkForInQuoted "for f in \"${!arr}\"; do true; done"-prop_checkForInQuoted7 = verify checkForInQuoted "for f in ls, grep, mv; do true; done"-prop_checkForInQuoted8 = verify checkForInQuoted "for f in 'ls', 'grep', 'mv'; do true; done"-prop_checkForInQuoted9 = verifyNot checkForInQuoted "for f in 'ls,' 'grep,' 'mv'; do true; done"-checkForInQuoted _ (T_ForIn _ f [T_NormalWord _ [word@(T_DoubleQuoted id list)]] _)- | any willSplit list && not (mayBecomeMultipleArgs word)- || maybe False wouldHaveBeenGlob (getLiteralString word) =- err id 2066 "Since you double quoted this, it will not word split, and the loop will only run once."-checkForInQuoted _ (T_ForIn _ f [T_NormalWord _ [T_SingleQuoted id _]] _) =- warn id 2041 "This is a literal string. To run as a command, use $(..) instead of '..' . "-checkForInQuoted _ (T_ForIn _ _ [single] _)- | maybe False (',' `elem`) $ getUnquotedLiteral single =- warn (getId single) 2042 "Use spaces, not commas, to separate loop elements."- | not (willSplit single || mayBecomeMultipleArgs single) =- warn (getId single) 2043 "This loop will only ever run once. Bad quoting or missing glob/expansion?"-checkForInQuoted params (T_ForIn _ _ multiple _) =- forM_ multiple $ \arg -> sequence_ $ do- suffix <- getTrailingUnquotedLiteral arg- string <- getLiteralString suffix- guard $ "," `isSuffixOf` string- return $- warnWithFix (getId arg) 2258- "The trailing comma is part of the value, not a separator. Delete or quote it."- (fixWith [replaceEnd (getId suffix) params 1 ""])-checkForInQuoted _ _ = return ()--prop_checkForInCat1 = verify checkForInCat "for f in $(cat foo); do stuff; done"-prop_checkForInCat1a = verify checkForInCat "for f in `cat foo`; do stuff; done"-prop_checkForInCat2 = verify checkForInCat "for f in $(cat foo | grep lol); do stuff; done"-prop_checkForInCat2a = verify checkForInCat "for f in `cat foo | grep lol`; do stuff; done"-prop_checkForInCat3 = verifyNot checkForInCat "for f in $(cat foo | grep bar | wc -l); do stuff; done"-checkForInCat _ (T_ForIn _ f [T_NormalWord _ w] _) = mapM_ checkF w- where- checkF (T_DollarExpansion id [T_Pipeline _ _ r])- | all isLineBased r =- info id 2013 "To read lines rather than words, pipe/redirect to a 'while read' loop."- checkF (T_Backticked id cmds) = checkF (T_DollarExpansion id cmds)- checkF _ = return ()- isLineBased cmd = any (cmd `isCommand`)- ["grep", "fgrep", "egrep", "sed", "cat", "awk", "cut", "sort"]-checkForInCat _ _ = return ()--prop_checkForInLs = verify checkForInLs "for f in $(ls *.mp3); do mplayer \"$f\"; done"-prop_checkForInLs2 = verify checkForInLs "for f in `ls *.mp3`; do mplayer \"$f\"; done"-prop_checkForInLs3 = verify checkForInLs "for f in `find / -name '*.mp3'`; do mplayer \"$f\"; done"-checkForInLs _ = try- where- try (T_ForIn _ f [T_NormalWord _ [T_DollarExpansion id [x]]] _) =- check id f x- try (T_ForIn _ f [T_NormalWord _ [T_Backticked id [x]]] _) =- check id f x- try _ = return ()- check id f x =- case oversimplify x of- ("ls":n) ->- let warntype = if any ("-" `isPrefixOf`) n then warn else err in- warntype id 2045 "Iterating over ls output is fragile. Use globs."- ("find":_) -> warn id 2044 "For loops over find output are fragile. Use find -exec or a while read loop."- _ -> return ()---prop_checkFindExec1 = verify checkFindExec "find / -name '*.php' -exec rm {};"-prop_checkFindExec2 = verify checkFindExec "find / -exec touch {} && ls {} \\;"-prop_checkFindExec3 = verify checkFindExec "find / -execdir cat {} | grep lol +"-prop_checkFindExec4 = verifyNot checkFindExec "find / -name '*.php' -exec foo {} +"-prop_checkFindExec5 = verifyNot checkFindExec "find / -execdir bash -c 'a && b' \\;"-prop_checkFindExec6 = verify checkFindExec "find / -type d -execdir rm *.jpg \\;"-checkFindExec _ cmd@(T_SimpleCommand _ _ t@(h:r)) | cmd `isCommand` "find" = do- c <- broken r False- when c $- let wordId = getId $ last t in- err wordId 2067 "Missing ';' or + terminating -exec. You can't use |/||/&&, and ';' has to be a separate, quoted argument."-- where- broken [] v = return v- broken (w:r) v = do- when v (mapM_ warnFor $ fromWord w)- case getLiteralString w of- Just "-exec" -> broken r True- Just "-execdir" -> broken r True- Just "+" -> broken r False- Just ";" -> broken r False- _ -> broken r v-- shouldWarn x =- case x of- T_DollarExpansion _ _ -> True- T_Backticked _ _ -> True- T_Glob _ _ -> True- T_Extglob {} -> True- _ -> False-- warnFor x =- when(shouldWarn x) $- info (getId x) 2014 "This will expand once before find runs, not per file found."-- fromWord (T_NormalWord _ l) = l- fromWord _ = []-checkFindExec _ _ = return ()---prop_checkUnquotedExpansions1 = verify checkUnquotedExpansions "rm $(ls)"-prop_checkUnquotedExpansions1a = verify checkUnquotedExpansions "rm `ls`"-prop_checkUnquotedExpansions2 = verify checkUnquotedExpansions "rm foo$(date)"-prop_checkUnquotedExpansions3 = verify checkUnquotedExpansions "[ $(foo) == cow ]"-prop_checkUnquotedExpansions3a = verify checkUnquotedExpansions "[ ! $(foo) ]"-prop_checkUnquotedExpansions4 = verifyNot checkUnquotedExpansions "[[ $(foo) == cow ]]"-prop_checkUnquotedExpansions5 = verifyNot checkUnquotedExpansions "for f in $(cmd); do echo $f; done"-prop_checkUnquotedExpansions6 = verifyNot checkUnquotedExpansions "$(cmd)"-prop_checkUnquotedExpansions7 = verifyNot checkUnquotedExpansions "cat << foo\n$(ls)\nfoo"-prop_checkUnquotedExpansions8 = verifyNot checkUnquotedExpansions "set -- $(seq 1 4)"-prop_checkUnquotedExpansions9 = verifyNot checkUnquotedExpansions "echo foo `# inline comment`"-prop_checkUnquotedExpansions10 = verify checkUnquotedExpansions "#!/bin/sh\nexport var=$(val)"-prop_checkUnquotedExpansions11 = verifyNot checkUnquotedExpansions "ps -p $(pgrep foo)"-checkUnquotedExpansions params =- check- where- check t@(T_DollarExpansion _ c) = examine t c- check t@(T_Backticked _ c) = examine t c- check t@(T_DollarBraceCommandExpansion _ c) = examine t c- check _ = return ()- tree = parentMap params- examine t contents =- unless (null contents || shouldBeSplit t || isQuoteFree (shellType params) tree t || usedAsCommandName tree t) $- warn (getId t) 2046 "Quote this to prevent word splitting."-- shouldBeSplit t =- getCommandNameFromExpansion t `elem` [Just "seq", Just "pgrep"]---prop_checkRedirectToSame = verify checkRedirectToSame "cat foo > foo"-prop_checkRedirectToSame2 = verify checkRedirectToSame "cat lol | sed -e 's/a/b/g' > lol"-prop_checkRedirectToSame3 = verifyNot checkRedirectToSame "cat lol | sed -e 's/a/b/g' > foo.bar && mv foo.bar lol"-prop_checkRedirectToSame4 = verifyNot checkRedirectToSame "foo /dev/null > /dev/null"-prop_checkRedirectToSame5 = verifyNot checkRedirectToSame "foo > bar 2> bar"-prop_checkRedirectToSame6 = verifyNot checkRedirectToSame "echo foo > foo"-prop_checkRedirectToSame7 = verifyNot checkRedirectToSame "sed 's/foo/bar/g' file | sponge file"-prop_checkRedirectToSame8 = verifyNot checkRedirectToSame "while read -r line; do _=\"$fname\"; done <\"$fname\""-prop_checkRedirectToSame9 = verifyNot checkRedirectToSame "while read -r line; do cat < \"$fname\"; done <\"$fname\""-prop_checkRedirectToSame10 = verifyNot checkRedirectToSame "mapfile -t foo <foo"-checkRedirectToSame params s@(T_Pipeline _ _ list) =- mapM_ (\l -> (mapM_ (\x -> doAnalysis (checkOccurrences x) l) (getAllRedirs list))) list- where- note x = makeComment InfoC x 2094- "Make sure not to read and write the same file in the same pipeline."- checkOccurrences t@(T_NormalWord exceptId x) u@(T_NormalWord newId y) |- exceptId /= newId- && x == y- && not (isInput t && isInput u)- && not (isOutput t && isOutput u)- && not (special t)- && not (any isHarmlessCommand [t,u])- && not (any containsAssignment [u]) = do- addComment $ note newId- addComment $ note exceptId- checkOccurrences _ _ = return ()- getAllRedirs = concatMap (\t ->- case t of- T_Redirecting _ ls _ -> concatMap getRedirs ls- _ -> [])- getRedirs (T_FdRedirect _ _ (T_IoFile _ op file)) =- case op of T_Greater _ -> [file]- T_Less _ -> [file]- T_DGREAT _ -> [file]- _ -> []- getRedirs _ = []- special x = "/dev/" `isPrefixOf` concat (oversimplify x)- isInput t =- case drop 1 $ getPath (parentMap params) t of- T_IoFile _ op _:_ ->- case op of- T_Less _ -> True- _ -> False- _ -> False- isOutput t =- case drop 1 $ getPath (parentMap params) t of- T_IoFile _ op _:_ ->- case op of- T_Greater _ -> True- T_DGREAT _ -> True- _ -> False- _ -> False- isHarmlessCommand arg = fromMaybe False $ do- cmd <- getClosestCommand (parentMap params) arg- name <- getCommandBasename cmd- return $ name `elem` ["echo", "mapfile", "printf", "sponge"]- containsAssignment arg = fromMaybe False $ do- cmd <- getClosestCommand (parentMap params) arg- return $ isAssignment cmd--checkRedirectToSame _ _ = return ()---prop_checkShorthandIf = verify checkShorthandIf "[[ ! -z file ]] && scp file host || rm file"-prop_checkShorthandIf2 = verifyNot checkShorthandIf "[[ ! -z file ]] && { scp file host || echo 'Eek'; }"-prop_checkShorthandIf3 = verifyNot checkShorthandIf "foo && bar || echo baz"-prop_checkShorthandIf4 = verifyNot checkShorthandIf "foo && a=b || a=c"-prop_checkShorthandIf5 = verifyNot checkShorthandIf "foo && rm || printf b"-prop_checkShorthandIf6 = verifyNot checkShorthandIf "if foo && bar || baz; then true; fi"-prop_checkShorthandIf7 = verifyNot checkShorthandIf "while foo && bar || baz; do true; done"-prop_checkShorthandIf8 = verify checkShorthandIf "if true; then foo && bar || baz; fi"-checkShorthandIf params x@(T_OrIf _ (T_AndIf id _ _) (T_Pipeline _ _ t))- | not (isOk t || inCondition) =- info id 2015 "Note that A && B || C is not if-then-else. C may run when A is true."- where- isOk [t] = isAssignment t || fromMaybe False (do- name <- getCommandBasename t- return $ name `elem` ["echo", "exit", "return", "printf"])- isOk _ = False- inCondition = isCondition $ getPath (parentMap params) x-checkShorthandIf _ _ = return ()---prop_checkDollarStar = verify checkDollarStar "for f in $*; do ..; done"-prop_checkDollarStar2 = verifyNot checkDollarStar "a=$*"-prop_checkDollarStar3 = verifyNot checkDollarStar "[[ $* = 'a b' ]]"-prop_checkDollarStar4 = verify checkDollarStar "for f in ${var[*]}; do ..; done"-prop_checkDollarStar5 = verify checkDollarStar "ls ${*//foo/bar}"-prop_checkDollarStar6 = verify checkDollarStar "ls ${var[*]%%.*}"-prop_checkDollarStar7 = verify checkDollarStar "ls ${*}"-prop_checkDollarStar8 = verifyNot checkDollarStar "ls ${#*}"-prop_checkDollarStar9 = verify checkDollarStar "ls ${arr[*]}"-prop_checkDollarStar10 = verifyNot checkDollarStar "ls ${#arr[*]}"-checkDollarStar p t@(T_NormalWord _ [T_DollarBraced id _ l])- | not (isStrictlyQuoteFree (shellType p) (parentMap p) t) = do- let str = concat (oversimplify l)- when ("*" `isPrefixOf` str) $- warn id 2048 "Use \"$@\" (with quotes) to prevent whitespace problems."- when ("[*]" `isPrefixOf` (getBracedModifier str) && isVariableChar (headOrDefault '!' str)) $- warn id 2048 "Use \"${array[@]}\" (with quotes) to prevent whitespace problems."--checkDollarStar _ _ = return ()---prop_checkUnquotedDollarAt = verify checkUnquotedDollarAt "ls $@"-prop_checkUnquotedDollarAt1 = verifyNot checkUnquotedDollarAt "ls ${#@}"-prop_checkUnquotedDollarAt2 = verify checkUnquotedDollarAt "ls ${foo[@]}"-prop_checkUnquotedDollarAt3 = verifyNot checkUnquotedDollarAt "ls ${#foo[@]}"-prop_checkUnquotedDollarAt4 = verifyNot checkUnquotedDollarAt "ls \"$@\""-prop_checkUnquotedDollarAt5 = verifyNot checkUnquotedDollarAt "ls ${foo/@/ at }"-prop_checkUnquotedDollarAt6 = verifyNot checkUnquotedDollarAt "a=$@"-prop_checkUnquotedDollarAt7 = verify checkUnquotedDollarAt "for f in ${var[@]}; do true; done"-prop_checkUnquotedDollarAt8 = verifyNot checkUnquotedDollarAt "echo \"${args[@]:+${args[@]}}\""-prop_checkUnquotedDollarAt9 = verifyNot checkUnquotedDollarAt "echo ${args[@]:+\"${args[@]}\"}"-prop_checkUnquotedDollarAt10 = verifyNot checkUnquotedDollarAt "echo ${@+\"$@\"}"-checkUnquotedDollarAt p word@(T_NormalWord _ parts) | not $ isStrictlyQuoteFree (shellType p) (parentMap p) word =- forM_ (find isArrayExpansion parts) $ \x ->- unless (isQuotedAlternativeReference x) $- err (getId x) 2068- "Double quote array expansions to avoid re-splitting elements."-checkUnquotedDollarAt _ _ = return ()--prop_checkConcatenatedDollarAt1 = verify checkConcatenatedDollarAt "echo \"foo$@\""-prop_checkConcatenatedDollarAt2 = verify checkConcatenatedDollarAt "echo ${arr[@]}lol"-prop_checkConcatenatedDollarAt3 = verify checkConcatenatedDollarAt "echo $a$@"-prop_checkConcatenatedDollarAt4 = verifyNot checkConcatenatedDollarAt "echo $@"-prop_checkConcatenatedDollarAt5 = verifyNot checkConcatenatedDollarAt "echo \"${arr[@]}\""-checkConcatenatedDollarAt p word@T_NormalWord {}- | not $ isQuoteFree (shellType p) (parentMap p) word- || null (drop 1 parts) =- mapM_ for array- where- parts = getWordParts word- array = find isArrayExpansion parts- for t = err (getId t) 2145 "Argument mixes string and array. Use * or separate argument."-checkConcatenatedDollarAt _ _ = return ()--prop_checkArrayAsString1 = verify checkArrayAsString "a=$@"-prop_checkArrayAsString2 = verify checkArrayAsString "a=\"${arr[@]}\""-prop_checkArrayAsString3 = verify checkArrayAsString "a=*.png"-prop_checkArrayAsString4 = verify checkArrayAsString "a={1..10}"-prop_checkArrayAsString5 = verifyNot checkArrayAsString "a='*.gif'"-prop_checkArrayAsString6 = verifyNot checkArrayAsString "a=$*"-prop_checkArrayAsString7 = verifyNot checkArrayAsString "a=( $@ )"-checkArrayAsString _ (T_Assignment id _ _ _ word) =- if willConcatInAssignment word- then- warn (getId word) 2124- "Assigning an array to a string! Assign as array, or use * instead of @ to concatenate."- else- when (willBecomeMultipleArgs word) $- warn (getId word) 2125- "Brace expansions and globs are literal in assignments. Quote it or use an array."-checkArrayAsString _ _ = return ()--prop_checkArrayWithoutIndex1 = verifyTree checkArrayWithoutIndex "foo=(a b); echo $foo"-prop_checkArrayWithoutIndex2 = verifyNotTree checkArrayWithoutIndex "foo='bar baz'; foo=($foo); echo ${foo[0]}"-prop_checkArrayWithoutIndex3 = verifyTree checkArrayWithoutIndex "coproc foo while true; do echo cow; done; echo $foo"-prop_checkArrayWithoutIndex4 = verifyTree checkArrayWithoutIndex "coproc tail -f log; echo $COPROC"-prop_checkArrayWithoutIndex5 = verifyTree checkArrayWithoutIndex "a[0]=foo; echo $a"-prop_checkArrayWithoutIndex6 = verifyTree checkArrayWithoutIndex "echo $PIPESTATUS"-prop_checkArrayWithoutIndex7 = verifyTree checkArrayWithoutIndex "a=(a b); a+=c"-prop_checkArrayWithoutIndex8 = verifyTree checkArrayWithoutIndex "declare -a foo; foo=bar;"-prop_checkArrayWithoutIndex9 = verifyTree checkArrayWithoutIndex "read -r -a arr <<< 'foo bar'; echo \"$arr\""-prop_checkArrayWithoutIndex10 = verifyTree checkArrayWithoutIndex "read -ra arr <<< 'foo bar'; echo \"$arr\""-prop_checkArrayWithoutIndex11 = verifyNotTree checkArrayWithoutIndex "read -rpfoobar r; r=42"-checkArrayWithoutIndex params _ =- doVariableFlowAnalysis readF writeF defaultMap (variableFlow params)- where- defaultMap = Map.fromList $ map (\x -> (x,())) arrayVariables- readF _ (T_DollarBraced id _ token) _ = do- map <- get- return . maybeToList $ do- name <- getLiteralString token- assigned <- Map.lookup name map- return $ makeComment WarningC id 2128- "Expanding an array without an index only gives the first element."- readF _ _ _ = return []-- writeF _ (T_Assignment id mode name [] _) _ (DataString _) = do- isArray <- gets (Map.member name)- return $ if not isArray then [] else- case mode of- Assign -> [makeComment WarningC id 2178 "Variable was used as an array but is now assigned a string."]- Append -> [makeComment WarningC id 2179 "Use array+=(\"item\") to append items to an array."]-- writeF _ t name (DataArray _) = do- modify (Map.insert name ())- return []- writeF _ expr name _ = do- if isIndexed expr- then modify (Map.insert name ())- else modify (Map.delete name)- return []-- isIndexed expr =- case expr of- T_Assignment _ _ _ (_:_) _ -> True- _ -> False--prop_checkStderrRedirect = verify checkStderrRedirect "test 2>&1 > cow"-prop_checkStderrRedirect2 = verifyNot checkStderrRedirect "test > cow 2>&1"-prop_checkStderrRedirect3 = verifyNot checkStderrRedirect "test 2>&1 > file | grep stderr"-prop_checkStderrRedirect4 = verifyNot checkStderrRedirect "errors=$(test 2>&1 > file)"-prop_checkStderrRedirect5 = verifyNot checkStderrRedirect "read < <(test 2>&1 > file)"-prop_checkStderrRedirect6 = verify checkStderrRedirect "foo | bar 2>&1 > /dev/null"-prop_checkStderrRedirect7 = verifyNot checkStderrRedirect "{ cmd > file; } 2>&1"-checkStderrRedirect params redir@(T_Redirecting _ [- T_FdRedirect id "2" (T_IoDuplicate _ (T_GREATAND _) "1"),- T_FdRedirect _ _ (T_IoFile _ op _)- ] _) = case op of- T_Greater _ -> error- T_DGREAT _ -> error- _ -> return ()- where- usesOutput t =- case t of- (T_Pipeline _ _ list) -> length list > 1 && not (isParentOf (parentMap params) (last list) redir)- T_ProcSub {} -> True- T_DollarExpansion {} -> True- T_Backticked {} -> True- _ -> False- isCaptured = any usesOutput $ getPath (parentMap params) redir-- error = unless isCaptured $- warn id 2069 "To redirect stdout+stderr, 2>&1 must be last (or use '{ cmd > file; } 2>&1' to clarify)."--checkStderrRedirect _ _ = return ()--lt x = trace ("Tracing " ++ show x) x -- STRIP-ltt t = trace ("Tracing " ++ show t) -- STRIP---prop_checkSingleQuotedVariables = verify checkSingleQuotedVariables "echo '$foo'"-prop_checkSingleQuotedVariables2 = verify checkSingleQuotedVariables "echo 'lol$1.jpg'"-prop_checkSingleQuotedVariables3 = verifyNot checkSingleQuotedVariables "sed 's/foo$/bar/'"-prop_checkSingleQuotedVariables3a = verify checkSingleQuotedVariables "sed 's/${foo}/bar/'"-prop_checkSingleQuotedVariables3b = verify checkSingleQuotedVariables "sed 's/$(echo cow)/bar/'"-prop_checkSingleQuotedVariables3c = verify checkSingleQuotedVariables "sed 's/$((1+foo))/bar/'"-prop_checkSingleQuotedVariables4 = verifyNot checkSingleQuotedVariables "awk '{print $1}'"-prop_checkSingleQuotedVariables5 = verifyNot checkSingleQuotedVariables "trap 'echo $SECONDS' EXIT"-prop_checkSingleQuotedVariables6 = verifyNot checkSingleQuotedVariables "sed -n '$p'"-prop_checkSingleQuotedVariables6a = verify checkSingleQuotedVariables "sed -n '$pattern'"-prop_checkSingleQuotedVariables7 = verifyNot checkSingleQuotedVariables "PS1='$PWD \\$ '"-prop_checkSingleQuotedVariables8 = verify checkSingleQuotedVariables "find . -exec echo '$1' {} +"-prop_checkSingleQuotedVariables9 = verifyNot checkSingleQuotedVariables "find . -exec awk '{print $1}' {} \\;"-prop_checkSingleQuotedVariables10 = verify checkSingleQuotedVariables "echo '`pwd`'"-prop_checkSingleQuotedVariables11 = verifyNot checkSingleQuotedVariables "sed '${/lol/d}'"-prop_checkSingleQuotedVariables12 = verifyNot checkSingleQuotedVariables "eval 'echo $1'"-prop_checkSingleQuotedVariables13 = verifyNot checkSingleQuotedVariables "busybox awk '{print $1}'"-prop_checkSingleQuotedVariables14 = verifyNot checkSingleQuotedVariables "[ -v 'bar[$foo]' ]"-prop_checkSingleQuotedVariables15 = verifyNot checkSingleQuotedVariables "git filter-branch 'test $GIT_COMMIT'"-prop_checkSingleQuotedVariables16 = verify checkSingleQuotedVariables "git '$a'"-prop_checkSingleQuotedVariables17 = verifyNot checkSingleQuotedVariables "rename 's/(.)a/$1/g' *"-prop_checkSingleQuotedVariables18 = verifyNot checkSingleQuotedVariables "echo '``'"-prop_checkSingleQuotedVariables19 = verifyNot checkSingleQuotedVariables "echo '```'"-prop_checkSingleQuotedVariables20 = verifyNot checkSingleQuotedVariables "mumps -run %XCMD 'W $O(^GLOBAL(5))'"-prop_checkSingleQuotedVariables21 = verifyNot checkSingleQuotedVariables "mumps -run LOOP%XCMD --xec 'W $O(^GLOBAL(6))'"-prop_checkSingleQuotedVariables22 = verifyNot checkSingleQuotedVariables "jq '$__loc__'"-prop_checkSingleQuotedVariables23 = verifyNot checkSingleQuotedVariables "command jq '$__loc__'"-prop_checkSingleQuotedVariables24 = verifyNot checkSingleQuotedVariables "exec jq '$__loc__'"-prop_checkSingleQuotedVariables25 = verifyNot checkSingleQuotedVariables "exec -c -a foo jq '$__loc__'"---checkSingleQuotedVariables params t@(T_SingleQuoted id s) =- when (s `matches` re) $- if "sed" == commandName- then unless (s `matches` sedContra) showMessage- else unless isProbablyOk showMessage- where- parents = parentMap params- showMessage = info id 2016- "Expressions don't expand in single quotes, use double quotes for that."- commandName = fromMaybe "" $ do- cmd <- getClosestCommand parents t- name <- getCommandBasename cmd- return $ if name == "find" then getFindCommand cmd else if name == "git" then getGitCommand cmd else if name == "mumps" then getMumpsCommand cmd else name-- isProbablyOk =- any isOkAssignment (take 3 $ getPath parents t)- || commandName `elem` [- "trap"- ,"sh"- ,"bash"- ,"ksh"- ,"zsh"- ,"ssh"- ,"eval"- ,"xprop"- ,"alias"- ,"sudo" -- covering "sudo sh" and such- ,"docker" -- like above- ,"podman"- ,"dpkg-query"- ,"jq" -- could also check that user provides --arg- ,"rename"- ,"rg"- ,"unset"- ,"git filter-branch"- ,"mumps -run %XCMD"- ,"mumps -run LOOP%XCMD"- ]- || "awk" `isSuffixOf` commandName- || "perl" `isPrefixOf` commandName-- commonlyQuoted = ["PS1", "PS2", "PS3", "PS4", "PROMPT_COMMAND"]- isOkAssignment t =- case t of- T_Assignment _ _ name _ _ -> name `elem` commonlyQuoted- TC_Unary _ _ "-v" _ -> True- _ -> False-- re = mkRegex "\\$[{(0-9a-zA-Z_]|`[^`]+`"- sedContra = mkRegex "\\$[{dpsaic]($|[^a-zA-Z])"-- getFindCommand (T_SimpleCommand _ _ words) =- let list = map getLiteralString words- cmd = dropWhile (\x -> x /= Just "-exec" && x /= Just "-execdir") list- in- case cmd of- (flag:cmd:rest) -> fromMaybe "find" cmd- _ -> "find"- getFindCommand (T_Redirecting _ _ cmd) = getFindCommand cmd- getFindCommand _ = "find"- getGitCommand (T_SimpleCommand _ _ words) =- case map getLiteralString words of- Just "git":Just "filter-branch":_ -> "git filter-branch"- _ -> "git"- getGitCommand (T_Redirecting _ _ cmd) = getGitCommand cmd- getGitCommand _ = "git"- getMumpsCommand (T_SimpleCommand _ _ words) =- case map getLiteralString words of- Just "mumps":Just "-run":Just "%XCMD":_ -> "mumps -run %XCMD"- Just "mumps":Just "-run":Just "LOOP%XCMD":_ -> "mumps -run LOOP%XCMD"- _ -> "mumps"- getMumpsCommand (T_Redirecting _ _ cmd) = getMumpsCommand cmd- getMumpsCommand _ = "mumps"-checkSingleQuotedVariables _ _ = return ()---prop_checkUnquotedN = verify checkUnquotedN "if [ -n $foo ]; then echo cow; fi"-prop_checkUnquotedN2 = verify checkUnquotedN "[ -n $cow ]"-prop_checkUnquotedN3 = verifyNot checkUnquotedN "[[ -n $foo ]] && echo cow"-prop_checkUnquotedN4 = verify checkUnquotedN "[ -n $cow -o -t 1 ]"-prop_checkUnquotedN5 = verifyNot checkUnquotedN "[ -n \"$@\" ]"-checkUnquotedN _ (TC_Unary _ SingleBracket "-n" t) | willSplit t =- unless (any isArrayExpansion $ getWordParts t) $ -- There's SC2198 for these- err (getId t) 2070 "-n doesn't work with unquoted arguments. Quote or use [[ ]]."-checkUnquotedN _ _ = return ()--prop_checkNumberComparisons1 = verify checkNumberComparisons "[[ $foo < 3 ]]"-prop_checkNumberComparisons2 = verify checkNumberComparisons "[[ 0 >= $(cmd) ]]"-prop_checkNumberComparisons3 = verifyNot checkNumberComparisons "[[ $foo ]] > 3"-prop_checkNumberComparisons4 = verify checkNumberComparisons "[[ $foo > 2.72 ]]"-prop_checkNumberComparisons5 = verify checkNumberComparisons "[[ $foo -le 2.72 ]]"-prop_checkNumberComparisons6 = verify checkNumberComparisons "[[ 3.14 -eq $foo ]]"-prop_checkNumberComparisons7 = verifyNot checkNumberComparisons "[[ 3.14 == $foo ]]"-prop_checkNumberComparisons8 = verify checkNumberComparisons "[ foo <= bar ]"-prop_checkNumberComparisons9 = verify checkNumberComparisons "[ foo \\>= bar ]"-prop_checkNumberComparisons11 = verify checkNumberComparisons "[ $foo -eq 'N' ]"-prop_checkNumberComparisons12 = verify checkNumberComparisons "[ x$foo -gt x${N} ]"-prop_checkNumberComparisons13 = verify checkNumberComparisons "[ $foo > $bar ]"-prop_checkNumberComparisons14 = verifyNot checkNumberComparisons "[[ foo < bar ]]"-prop_checkNumberComparisons15 = verifyNot checkNumberComparisons "[ $foo '>' $bar ]"-prop_checkNumberComparisons16 = verify checkNumberComparisons "[ foo -eq 'y' ]"-prop_checkNumberComparisons17 = verify checkNumberComparisons "[[ 'foo' -eq 2 ]]"-prop_checkNumberComparisons18 = verify checkNumberComparisons "[[ foo -eq 2 ]]"-prop_checkNumberComparisons19 = verifyNot checkNumberComparisons "foo=1; [[ foo -eq 2 ]]"-prop_checkNumberComparisons20 = verify checkNumberComparisons "[[ 2 -eq / ]]"-prop_checkNumberComparisons21 = verify checkNumberComparisons "[[ foo -eq foo ]]"-prop_checkNumberComparisons22 = verify checkNumberComparisons "x=10; [[ $x > $z ]]"-prop_checkNumberComparisons23 = verify checkNumberComparisons "x=0; if [[ -n $def ]]; then x=$def; fi; while [ $x > $z ]; do lol; done"-prop_checkNumberComparisons24 = verify checkNumberComparisons "x=$RANDOM; [ $x > $z ]"-prop_checkNumberComparisons25 = verify checkNumberComparisons "[[ $((n++)) > $x ]]"--checkNumberComparisons params (TC_Binary id typ op lhs rhs) = do- if isNum lhs || isNum rhs- then do- when (isLtGt op) $- err id 2071 $- op ++ " is for string comparisons. Use " ++ eqv op ++ " instead."- when (isLeGe op && hasStringComparison) $- err id 2071 $ op ++ " is not a valid operator. " ++- "Use " ++ eqv op ++ " ."- else do- when (isLeGe op || isLtGt op) $- mapM_ checkDecimals [lhs, rhs]-- when (isLeGe op && hasStringComparison) $- err id 2122 $ op ++ " is not a valid operator. " ++- "Use '! a " ++ esc ++ invert op ++ " b' instead."-- when (typ == SingleBracket && op `elem` ["<", ">"]) $- case shellType params of- Sh -> return () -- These are unsupported and will be caught by bashism checks.- Dash -> err id 2073 $ "Escape \\" ++ op ++ " to prevent it redirecting."- _ -> err id 2073 $ "Escape \\" ++ op ++ " to prevent it redirecting (or switch to [[ .. ]])."-- when (op `elem` arithmeticBinaryTestOps) $ do- mapM_ checkDecimals [lhs, rhs]- mapM_ checkString [lhs, rhs]--- where- hasStringComparison = shellType params /= Sh- isLtGt = flip elem ["<", "\\<", ">", "\\>"]- isLeGe = flip elem ["<=", "\\<=", ">=", "\\>="]-- checkDecimals hs =- when (isFraction hs && not (hasFloatingPoint params)) $- err (getId hs) 2072 decimalError- decimalError = "Decimals are not supported. " ++- "Either use integers only, or use bc or awk to compare."-- checkString t =- let- asString = getLiteralStringDef "\0" t- isVar = isVariableName asString- kind = if isVar then "a variable" else "an arithmetic expression"- fix = if isVar then "$var" else "$((expr))"- in- when (isNonNum t) $- if typ == SingleBracket- then- err (getId t) 2170 $- "Invalid number for " ++ op ++ ". Use " ++ seqv op ++- " to compare as string (or use " ++ fix ++- " to expand as " ++ kind ++ ")."- else- -- We should warn if any of the following holds:- -- The string is not a variable name- -- Any part of it is quoted- -- It's not a recognized variable name- when (not isVar || any isQuotes (getWordParts t) || asString `notElem` assignedVariables) $- warn (getId t) 2309 $- op ++ " treats this as " ++ kind ++ ". " ++- "Use " ++ seqv op ++ " to compare as string (or expand explicitly with " ++ fix ++ ")."-- assignedVariables :: [String]- assignedVariables = mapMaybe f (variableFlow params)- where- f t = do- Assignment (_, _, name, _) <- return t- return name-- isNonNum t = not . all numChar $ onlyLiteralString t- numChar x = isDigit x || x `elem` "+-. "-- isNum t =- case getWordParts t of- [T_DollarArithmetic {}] -> True- [b@(T_DollarBraced id _ c)] ->- let- str = concat $ oversimplify c- var = getBracedReference str- in fromMaybe False $ do- state <- CF.getIncomingState (cfgAnalysis params) id- value <- Map.lookup var $ CF.variablesInScope state- return $ CF.numericalStatus (CF.variableValue value) >= CF.NumericalStatusMaybe- _ ->- case oversimplify t of- [v] -> all isDigit v- _ -> False-- isFraction t =- case oversimplify t of- [v] -> isJust $ matchRegex floatRegex v- _ -> False-- eqv ('\\':s) = eqv s- eqv "<" = "-lt"- eqv ">" = "-gt"- eqv "<=" = "-le"- eqv ">=" = "-ge"- eqv _ = "the numerical equivalent"-- esc = if typ == SingleBracket then "\\" else ""- seqv "-ge" = "! a " ++ esc ++ "< b"- seqv "-gt" = esc ++ ">"- seqv "-le" = "! a " ++ esc ++ "> b"- seqv "-lt" = esc ++ "<"- seqv "-eq" = "="- seqv "-ne" = "!="- seqv _ = "the string equivalent"-- invert ('\\':s) = invert s- invert "<=" = ">"- invert ">=" = "<"-- floatRegex = mkRegex "^[-+]?[0-9]+\\.[0-9]+$"-checkNumberComparisons _ _ = return ()--prop_checkSingleBracketOperators1 = verify checkSingleBracketOperators "[ test =~ foo ]"-checkSingleBracketOperators params (TC_Binary id SingleBracket "=~" lhs rhs)- | shellType params `elem` [Bash, Ksh] =- err id 2074 $ "Can't use =~ in [ ]. Use [[..]] instead."-checkSingleBracketOperators _ _ = return ()--prop_checkDoubleBracketOperators1 = verify checkDoubleBracketOperators "[[ 3 \\< 4 ]]"-prop_checkDoubleBracketOperators3 = verifyNot checkDoubleBracketOperators "[[ foo < bar ]]"-checkDoubleBracketOperators _ x@(TC_Binary id typ op lhs rhs)- | typ == DoubleBracket && op `elem` ["\\<", "\\>"] =- err id 2075 $ "Escaping " ++ op ++" is required in [..], but invalid in [[..]]"-checkDoubleBracketOperators _ _ = return ()--prop_checkConditionalAndOrs1 = verify checkConditionalAndOrs "[ foo && bar ]"-prop_checkConditionalAndOrs2 = verify checkConditionalAndOrs "[[ foo -o bar ]]"-prop_checkConditionalAndOrs3 = verifyNot checkConditionalAndOrs "[[ foo || bar ]]"-prop_checkConditionalAndOrs4 = verify checkConditionalAndOrs "[ foo -a bar ]"-prop_checkConditionalAndOrs5 = verify checkConditionalAndOrs "[ -z 3 -o a = b ]"-checkConditionalAndOrs _ t =- case t of- (TC_And id SingleBracket "&&" _ _) ->- err id 2107 "Instead of [ a && b ], use [ a ] && [ b ]."- (TC_And id DoubleBracket "-a" _ _) ->- err id 2108 "In [[..]], use && instead of -a."- (TC_Or id SingleBracket "||" _ _) ->- err id 2109 "Instead of [ a || b ], use [ a ] || [ b ]."- (TC_Or id DoubleBracket "-o" _ _) ->- err id 2110 "In [[..]], use || instead of -o."-- (TC_And id SingleBracket "-a" _ _) ->- warn id 2166 "Prefer [ p ] && [ q ] as [ p -a q ] is not well defined."- (TC_Or id SingleBracket "-o" _ _) ->- warn id 2166 "Prefer [ p ] || [ q ] as [ p -o q ] is not well defined."-- _ -> return ()--prop_checkQuotedCondRegex1 = verify checkQuotedCondRegex "[[ $foo =~ \"bar.*\" ]]"-prop_checkQuotedCondRegex2 = verify checkQuotedCondRegex "[[ $foo =~ '(cow|bar)' ]]"-prop_checkQuotedCondRegex3 = verifyNot checkQuotedCondRegex "[[ $foo =~ $foo ]]"-prop_checkQuotedCondRegex4 = verifyNot checkQuotedCondRegex "[[ $foo =~ \"bar\" ]]"-prop_checkQuotedCondRegex5 = verifyNot checkQuotedCondRegex "[[ $foo =~ 'cow bar' ]]"-prop_checkQuotedCondRegex6 = verify checkQuotedCondRegex "[[ $foo =~ 'cow|bar' ]]"-checkQuotedCondRegex _ (TC_Binary _ _ "=~" _ rhs) =- case rhs of- T_NormalWord id [T_DoubleQuoted _ _] -> error rhs- T_NormalWord id [T_SingleQuoted _ _] -> error rhs- _ -> return ()- where- error t =- unless (isConstantNonRe t) $- warn (getId t) 2076- "Remove quotes from right-hand side of =~ to match as a regex rather than literally."- re = mkRegex "[][*.+()|]"- hasMetachars s = s `matches` re- isConstantNonRe t = fromMaybe False $ do- s <- getLiteralString t- return . not $ hasMetachars s-checkQuotedCondRegex _ _ = return ()--prop_checkGlobbedRegex1 = verify checkGlobbedRegex "[[ $foo =~ *foo* ]]"-prop_checkGlobbedRegex2 = verify checkGlobbedRegex "[[ $foo =~ f* ]]"-prop_checkGlobbedRegex3 = verifyNot checkGlobbedRegex "[[ $foo =~ $foo ]]"-prop_checkGlobbedRegex4 = verifyNot checkGlobbedRegex "[[ $foo =~ ^c.* ]]"-prop_checkGlobbedRegex5 = verifyNot checkGlobbedRegex "[[ $foo =~ \\* ]]"-prop_checkGlobbedRegex6 = verifyNot checkGlobbedRegex "[[ $foo =~ (o*) ]]"-prop_checkGlobbedRegex7 = verifyNot checkGlobbedRegex "[[ $foo =~ \\*foo ]]"-prop_checkGlobbedRegex8 = verifyNot checkGlobbedRegex "[[ $foo =~ x\\* ]]"-checkGlobbedRegex _ (TC_Binary _ DoubleBracket "=~" _ rhs)- | isConfusedGlobRegex s =- warn (getId rhs) 2049 "=~ is for regex, but this looks like a glob. Use = instead."- where s = concat $ oversimplify rhs-checkGlobbedRegex _ _ = return ()---prop_checkConstantIfs1 = verify checkConstantIfs "[[ foo != bar ]]"-prop_checkConstantIfs2a = verify checkConstantIfs "[ n -le 4 ]"-prop_checkConstantIfs2b = verifyNot checkConstantIfs "[[ n -le 4 ]]"-prop_checkConstantIfs3 = verify checkConstantIfs "[[ $n -le 4 && n != 2 ]]"-prop_checkConstantIfs4 = verifyNot checkConstantIfs "[[ $n -le 3 ]]"-prop_checkConstantIfs5 = verifyNot checkConstantIfs "[[ $n -le $n ]]"-prop_checkConstantIfs6 = verifyNot checkConstantIfs "[[ a -ot b ]]"-prop_checkConstantIfs7 = verifyNot checkConstantIfs "[ a -nt b ]"-prop_checkConstantIfs8 = verifyNot checkConstantIfs "[[ ~foo == '~foo' ]]"-prop_checkConstantIfs9 = verify checkConstantIfs "[[ *.png == [a-z] ]]"-prop_checkConstantIfs10 = verifyNot checkConstantIfs "[[ ~me == ~+ ]]"-prop_checkConstantIfs11 = verifyNot checkConstantIfs "[[ ~ == ~+ ]]"-prop_checkConstantIfs12 = verify checkConstantIfs "[[ '~' == x ]]"-checkConstantIfs _ (TC_Binary id typ op lhs rhs) | not isDynamic =- if isConstant lhs && isConstant rhs- then warn id 2050 "This expression is constant. Did you forget the $ on a variable?"- else checkUnmatchable id op lhs rhs- where- isDynamic =- op `elem` arithmeticBinaryTestOps- && typ == DoubleBracket- || op `elem` [ "-nt", "-ot", "-ef"]-- checkUnmatchable id op lhs rhs =- when (op `elem` ["=", "==", "!="] && not (wordsCanBeEqual lhs rhs)) $- warn id 2193 "The arguments to this comparison can never be equal. Make sure your syntax is correct."-checkConstantIfs _ _ = return ()--prop_checkLiteralBreakingTest = verify checkLiteralBreakingTest "[[ a==$foo ]]"-prop_checkLiteralBreakingTest2 = verify checkLiteralBreakingTest "[ $foo=3 ]"-prop_checkLiteralBreakingTest3 = verify checkLiteralBreakingTest "[ $foo!=3 ]"-prop_checkLiteralBreakingTest4 = verify checkLiteralBreakingTest "[ \"$(ls) \" ]"-prop_checkLiteralBreakingTest5 = verify checkLiteralBreakingTest "[ -n \"$(true) \" ]"-prop_checkLiteralBreakingTest6 = verify checkLiteralBreakingTest "[ -z $(true)z ]"-prop_checkLiteralBreakingTest7 = verifyNot checkLiteralBreakingTest "[ -z $(true) ]"-prop_checkLiteralBreakingTest8 = verifyNot checkLiteralBreakingTest "[ $(true)$(true) ]"-prop_checkLiteralBreakingTest10 = verify checkLiteralBreakingTest "[ -z foo ]"-checkLiteralBreakingTest _ t = sequence_ $- case t of- (TC_Nullary _ _ w@(T_NormalWord _ l)) -> do- guard . not $ isConstant w -- Covered by SC2078- comparisonWarning l `mplus` tautologyWarning w "Argument to implicit -n is always true due to literal strings."- (TC_Unary _ _ op w@(T_NormalWord _ l)) ->- case op of- "-n" -> tautologyWarning w "Argument to -n is always true due to literal strings."- "-z" -> tautologyWarning w "Argument to -z is always false due to literal strings."- _ -> fail "not relevant"- _ -> fail "not my problem"- where- hasEquals = matchToken ('=' `elem`)- isNonEmpty = matchToken (not . null)- matchToken m t = maybe False m (getLiteralString t)-- comparisonWarning list = do- token <- find hasEquals list- return $ err (getId token) 2077 "You need spaces around the comparison operator."- tautologyWarning t s = do- token <- find isNonEmpty $ getWordParts t- return $ err (getId token) 2157 s--prop_checkConstantNullary = verify checkConstantNullary "[[ '$(foo)' ]]"-prop_checkConstantNullary2 = verify checkConstantNullary "[ \"-f lol\" ]"-prop_checkConstantNullary3 = verify checkConstantNullary "[[ cmd ]]"-prop_checkConstantNullary4 = verify checkConstantNullary "[[ ! cmd ]]"-prop_checkConstantNullary5 = verify checkConstantNullary "[[ true ]]"-prop_checkConstantNullary6 = verify checkConstantNullary "[ 1 ]"-prop_checkConstantNullary7 = verify checkConstantNullary "[ false ]"-checkConstantNullary _ (TC_Nullary _ _ t) | isConstant t =- case fromMaybe "" $ getLiteralString t of- "false" -> err (getId t) 2158 "[ false ] is true. Remove the brackets."- "0" -> err (getId t) 2159 "[ 0 ] is true. Use 'false' instead."- "true" -> style (getId t) 2160 "Instead of '[ true ]', just use 'true'."- "1" -> style (getId t) 2161 "Instead of '[ 1 ]', use 'true'."- _ -> err (getId t) 2078 "This expression is constant. Did you forget a $ somewhere?"- where- string = fromMaybe "" $ getLiteralString t--checkConstantNullary _ _ = return ()--prop_checkForDecimals1 = verify checkForDecimals "((3.14*c))"-prop_checkForDecimals2 = verify checkForDecimals "foo[1.2]=bar"-prop_checkForDecimals3 = verifyNot checkForDecimals "declare -A foo; foo[1.2]=bar"-checkForDecimals params t@(TA_Expansion id _) = sequence_ $ do- guard $ not (hasFloatingPoint params)- str <- getLiteralString t- first <- str !!! 0- guard $ isDigit first && '.' `elem` str- return $ err id 2079 "(( )) doesn't support decimals. Use bc or awk."-checkForDecimals _ _ = return ()--prop_checkDivBeforeMult = verify checkDivBeforeMult "echo $((c/n*100))"-prop_checkDivBeforeMult2 = verifyNot checkDivBeforeMult "echo $((c*100/n))"-prop_checkDivBeforeMult3 = verifyNot checkDivBeforeMult "echo $((c/10*10))"-checkDivBeforeMult params (TA_Binary _ "*" (TA_Binary id "/" _ x) y)- | not (hasFloatingPoint params) && x /= y =- info id 2017 "Increase precision by replacing a/b*c with a*c/b."-checkDivBeforeMult _ _ = return ()--prop_checkArithmeticDeref = verify checkArithmeticDeref "echo $((3+$foo))"-prop_checkArithmeticDeref2 = verify checkArithmeticDeref "cow=14; (( s+= $cow ))"-prop_checkArithmeticDeref3 = verifyNot checkArithmeticDeref "cow=1/40; (( s+= ${cow%%/*} ))"-prop_checkArithmeticDeref4 = verifyNot checkArithmeticDeref "(( ! $? ))"-prop_checkArithmeticDeref5 = verifyNot checkArithmeticDeref "(($1))"-prop_checkArithmeticDeref6 = verify checkArithmeticDeref "(( a[$i] ))"-prop_checkArithmeticDeref7 = verifyNot checkArithmeticDeref "(( 10#$n ))"-prop_checkArithmeticDeref8 = verifyNot checkArithmeticDeref "let i=$i+1"-prop_checkArithmeticDeref9 = verifyNot checkArithmeticDeref "(( a[foo] ))"-prop_checkArithmeticDeref10 = verifyNot checkArithmeticDeref "(( a[\\$foo] ))"-prop_checkArithmeticDeref11 = verify checkArithmeticDeref "a[$foo]=wee"-prop_checkArithmeticDeref11b = verifyNot checkArithmeticDeref "declare -A a; a[$foo]=wee"-prop_checkArithmeticDeref12 = verify checkArithmeticDeref "for ((i=0; $i < 3; i)); do true; done"-prop_checkArithmeticDeref13 = verifyNot checkArithmeticDeref "(( $$ ))"-prop_checkArithmeticDeref14 = verifyNot checkArithmeticDeref "(( $! ))"-prop_checkArithmeticDeref15 = verifyNot checkArithmeticDeref "(( ${!var} ))"-prop_checkArithmeticDeref16 = verifyNot checkArithmeticDeref "(( ${x+1} + ${x=42} ))"-checkArithmeticDeref params t@(TA_Expansion _ [T_DollarBraced id _ l]) =- unless (isException $ concat $ oversimplify l) getWarning- where- isException [] = True- isException s@(h:_) = any (`elem` "/.:#%?*@$-!+=^,") s || isDigit h- getWarning = fromMaybe noWarning . msum . map warningFor $ parents params t- warningFor t =- case t of- T_Arithmetic {} -> return normalWarning- T_DollarArithmetic {} -> return normalWarning- T_ForArithmetic {} -> return normalWarning- T_Assignment {} -> return normalWarning- T_SimpleCommand {} -> return noWarning- _ -> Nothing-- normalWarning = style id 2004 "$/${} is unnecessary on arithmetic variables."- noWarning = return ()-checkArithmeticDeref _ _ = return ()--prop_checkArithmeticBadOctal1 = verify checkArithmeticBadOctal "(( 0192 ))"-prop_checkArithmeticBadOctal2 = verifyNot checkArithmeticBadOctal "(( 0x192 ))"-prop_checkArithmeticBadOctal3 = verifyNot checkArithmeticBadOctal "(( 1 ^ 0777 ))"-checkArithmeticBadOctal _ t@(TA_Expansion id _) = sequence_ $ do- str <- getLiteralString t- guard $ str `matches` octalRE- return $ err id 2080 "Numbers with leading 0 are considered octal."- where- octalRE = mkRegex "^0[0-7]*[8-9]"-checkArithmeticBadOctal _ _ = return ()--prop_checkComparisonAgainstGlob = verify checkComparisonAgainstGlob "[[ $cow == $bar ]]"-prop_checkComparisonAgainstGlob2 = verifyNot checkComparisonAgainstGlob "[[ $cow == \"$bar\" ]]"-prop_checkComparisonAgainstGlob3 = verify checkComparisonAgainstGlob "[ $cow = *foo* ]"-prop_checkComparisonAgainstGlob4 = verifyNot checkComparisonAgainstGlob "[ $cow = foo ]"-prop_checkComparisonAgainstGlob5 = verify checkComparisonAgainstGlob "[[ $cow != $bar ]]"-prop_checkComparisonAgainstGlob6 = verify checkComparisonAgainstGlob "[ $f != /* ]"-checkComparisonAgainstGlob _ (TC_Binary _ DoubleBracket op _ (T_NormalWord id [T_DollarBraced _ _ _]))- | op `elem` ["=", "==", "!="] =- warn id 2053 $ "Quote the right-hand side of " ++ op ++ " in [[ ]] to prevent glob matching."-checkComparisonAgainstGlob params (TC_Binary _ SingleBracket op _ word)- | op `elem` ["=", "==", "!="] && isGlob word =- err (getId word) 2081 msg- where- msg = if isBashLike params- then "[ .. ] can't match globs. Use [[ .. ]] or case statement."- else "[ .. ] can't match globs. Use a case statement."--checkComparisonAgainstGlob _ _ = return ()--prop_checkCaseAgainstGlob1 = verify checkCaseAgainstGlob "case foo in lol$n) foo;; esac"-prop_checkCaseAgainstGlob2 = verify checkCaseAgainstGlob "case foo in $(foo)) foo;; esac"-prop_checkCaseAgainstGlob3 = verifyNot checkCaseAgainstGlob "case foo in *$bar*) foo;; esac"-checkCaseAgainstGlob _ t =- case t of- (T_CaseExpression _ _ cases) -> mapM_ check cases- _ -> return ()- where- check (_, list, _) = mapM_ check' list- check' expr@(T_NormalWord _ list)- -- If it's already a glob, assume that's what the user wanted- | not (isGlob expr) && any isQuoteableExpansion list =- warn (getId expr) 2254 "Quote expansions in case patterns to match literally rather than as a glob."- check' _ = return ()--prop_checkCommarrays1 = verify checkCommarrays "a=(1, 2)"-prop_checkCommarrays2 = verify checkCommarrays "a+=(1,2,3)"-prop_checkCommarrays3 = verifyNot checkCommarrays "cow=(1 \"foo,bar\" 3)"-prop_checkCommarrays4 = verifyNot checkCommarrays "cow=('one,' 'two')"-prop_checkCommarrays5 = verify checkCommarrays "a=([a]=b, [c]=d)"-prop_checkCommarrays6 = verify checkCommarrays "a=([a]=b,[c]=d,[e]=f)"-prop_checkCommarrays7 = verify checkCommarrays "a=(1,2)"-checkCommarrays _ (T_Array id l) =- when (any (isCommaSeparated . literal) l) $- warn id 2054 "Use spaces, not commas, to separate array elements."- where- literal (T_IndexedElement _ _ l) = literal l- literal (T_NormalWord _ l) = concatMap literal l- literal (T_Literal _ str) = str- literal _ = ""-- isCommaSeparated = elem ','-checkCommarrays _ _ = return ()--prop_checkOrNeq1 = verify checkOrNeq "if [[ $lol -ne cow || $lol -ne foo ]]; then echo foo; fi"-prop_checkOrNeq2 = verify checkOrNeq "(( a!=lol || a!=foo ))"-prop_checkOrNeq3 = verify checkOrNeq "[ \"$a\" != lol || \"$a\" != foo ]"-prop_checkOrNeq4 = verifyNot checkOrNeq "[ a != $cow || b != $foo ]"-prop_checkOrNeq5 = verifyNot checkOrNeq "[[ $a != /home || $a != */public_html/* ]]"-prop_checkOrNeq6 = verify checkOrNeq "[ $a != a ] || [ $a != b ]"-prop_checkOrNeq7 = verify checkOrNeq "[ $a != a ] || [ $a != b ] || true"-prop_checkOrNeq8 = verifyNot checkOrNeq "[[ $a != x || $a != x ]]"-prop_checkOrNeq9 = verifyNot checkOrNeq "[ 0 -ne $FOO ] || [ 0 -ne $BAR ]"--- This only catches the most idiomatic cases. Fixme?---- For test-level "or": [ x != y -o x != z ]-checkOrNeq _ (TC_Or id typ op (TC_Binary _ _ op1 lhs1 rhs1 ) (TC_Binary _ _ op2 lhs2 rhs2))- | (op1 == op2 && (op1 == "-ne" || op1 == "!=")) && lhs1 == lhs2 && rhs1 /= rhs2 && not (any isGlob [rhs1,rhs2]) =- warn id 2055 $ "You probably wanted " ++ (if typ == SingleBracket then "-a" else "&&") ++ " here, otherwise it's always true."---- For arithmetic context "or"-checkOrNeq _ (TA_Binary id "||" (TA_Binary _ "!=" word1 _) (TA_Binary _ "!=" word2 _))- | word1 == word2 =- warn id 2056 "You probably wanted && here, otherwise it's always true."---- For command level "or": [ x != y ] || [ x != z ]-checkOrNeq _ (T_OrIf id lhs rhs) = sequence_ $ do- (lhs1, op1, rhs1) <- getExpr lhs- (lhs2, op2, rhs2) <- getExpr rhs- guard $ op1 == op2 && op1 `elem` ["-ne", "!="]- guard $ lhs1 == lhs2 && rhs1 /= rhs2- guard . not $ any isGlob [rhs1, rhs2]- return $ warn id 2252 "You probably wanted && here, otherwise it's always true."- where- getExpr x =- case x of- T_OrIf _ lhs _ -> getExpr lhs -- Fetches x and y in `T_OrIf x (T_OrIf y z)`- T_Pipeline _ _ [x] -> getExpr x- T_Redirecting _ _ c -> getExpr c- T_Condition _ _ c -> getExpr c- TC_Binary _ _ op lhs rhs -> orient (lhs, op, rhs)- _ -> Nothing-- -- Swap items so that the constant side is rhs (or Nothing if both/neither is constant)- orient (lhs, op, rhs) =- case (isConstant lhs, isConstant rhs) of- (True, False) -> return (rhs, op, lhs)- (False, True) -> return (lhs, op, rhs)- _ -> Nothing---checkOrNeq _ _ = return ()---prop_checkValidCondOps1 = verify checkValidCondOps "[[ a -xz b ]]"-prop_checkValidCondOps2 = verify checkValidCondOps "[ -M a ]"-prop_checkValidCondOps2a = verifyNot checkValidCondOps "[ 3 \\> 2 ]"-prop_checkValidCondOps3 = verifyNot checkValidCondOps "[ 1 = 2 -a 3 -ge 4 ]"-prop_checkValidCondOps4 = verifyNot checkValidCondOps "[[ ! -v foo ]]"-checkValidCondOps _ (TC_Binary id _ s _ _)- | s `notElem` binaryTestOps =- warn id 2057 "Unknown binary operator."-checkValidCondOps _ (TC_Unary id _ s _)- | s `notElem` unaryTestOps =- warn id 2058 "Unknown unary operator."-checkValidCondOps _ _ = return ()--prop_checkUuoeVar1 = verify checkUuoeVar "for f in $(echo $tmp); do echo lol; done"-prop_checkUuoeVar2 = verify checkUuoeVar "date +`echo \"$format\"`"-prop_checkUuoeVar3 = verifyNot checkUuoeVar "foo \"$(echo -e '\r')\""-prop_checkUuoeVar4 = verifyNot checkUuoeVar "echo $tmp"-prop_checkUuoeVar5 = verify checkUuoeVar "foo \"$(echo \"$(date) value:\" $value)\""-prop_checkUuoeVar6 = verifyNot checkUuoeVar "foo \"$(echo files: *.png)\""-prop_checkUuoeVar7 = verifyNot checkUuoeVar "foo $(echo $(bar))" -- covered by 2005-prop_checkUuoeVar8 = verifyNot checkUuoeVar "#!/bin/sh\nz=$(echo)"-prop_checkUuoeVar9 = verify checkUuoeVar "foo $(echo $(<file))"-checkUuoeVar _ p =- case p of- T_Backticked id [cmd] -> check id cmd- T_DollarExpansion id [cmd] -> check id cmd- _ -> return ()- where- couldBeOptimized f = case f of- T_Glob {} -> False- T_Extglob {} -> False- T_BraceExpansion {} -> False- T_NormalWord _ l -> all couldBeOptimized l- T_DoubleQuoted _ l -> all couldBeOptimized l- _ -> True-- check id (T_Pipeline _ _ [T_Redirecting _ _ c]) = warnForEcho id c- check _ _ = return ()- isCovered first rest = null rest && tokenIsJustCommandOutput first- warnForEcho id = checkUnqualifiedCommand "echo" $ \_ vars ->- case vars of- (first:rest) ->- unless (isCovered first rest || "-" `isPrefixOf` onlyLiteralString first) $- when (all couldBeOptimized vars) $ style id 2116- "Useless echo? Instead of 'cmd $(echo foo)', just use 'cmd foo'."- _ -> return ()---prop_checkTestRedirects1 = verify checkTestRedirects "test 3 > 1"-prop_checkTestRedirects2 = verifyNot checkTestRedirects "test 3 \\> 1"-prop_checkTestRedirects3 = verify checkTestRedirects "/usr/bin/test $var > $foo"-prop_checkTestRedirects4 = verifyNot checkTestRedirects "test 1 -eq 2 2> file"-checkTestRedirects _ (T_Redirecting id redirs cmd) | cmd `isCommand` "test" =- mapM_ check redirs- where- check t =- when (suspicious t) $- warn (getId t) 2065 "This is interpreted as a shell file redirection, not a comparison."- suspicious t = -- Ignore redirections of stderr because these are valid for squashing e.g. int errors,- case t of -- and >> and similar redirections because these are probably not comparisons.- T_FdRedirect _ fd (T_IoFile _ op _) -> fd /= "2" && isComparison op- _ -> False- isComparison t =- case t of- T_Greater _ -> True- T_Less _ -> True- _ -> False-checkTestRedirects _ _ = return ()--prop_checkPS11 = verify checkPS1Assignments "PS1='\\033[1;35m\\$ '"-prop_checkPS11a = verify checkPS1Assignments "export PS1='\\033[1;35m\\$ '"-prop_checkPSf2 = verify checkPS1Assignments "PS1='\\h \\e[0m\\$ '"-prop_checkPS13 = verify checkPS1Assignments "PS1=$'\\x1b[c '"-prop_checkPS14 = verify checkPS1Assignments "PS1=$'\\e[3m; '"-prop_checkPS14a = verify checkPS1Assignments "export PS1=$'\\e[3m; '"-prop_checkPS15 = verifyNot checkPS1Assignments "PS1='\\[\\033[1;35m\\]\\$ '"-prop_checkPS16 = verifyNot checkPS1Assignments "PS1='\\[\\e1m\\e[1m\\]\\$ '"-prop_checkPS17 = verifyNot checkPS1Assignments "PS1='e033x1B'"-prop_checkPS18 = verifyNot checkPS1Assignments "PS1='\\[\\e\\]'"-checkPS1Assignments _ (T_Assignment _ _ "PS1" _ word) = warnFor word- where- warnFor word =- let contents = concat $ oversimplify word in- when (containsUnescaped contents) $- info (getId word) 2025 "Make sure all escape sequences are enclosed in \\[..\\] to prevent line wrapping issues"- containsUnescaped s =- let unenclosed = subRegex enclosedRegex s "" in- isJust $ matchRegex escapeRegex unenclosed- enclosedRegex = mkRegex "\\\\\\[.*\\\\\\]" -- FIXME: shouldn't be eager- escapeRegex = mkRegex "\\\\x1[Bb]|\\\\e|\x1B|\\\\033"-checkPS1Assignments _ _ = return ()--prop_checkBackticks1 = verify checkBackticks "echo `foo`"-prop_checkBackticks2 = verifyNot checkBackticks "echo $(foo)"-prop_checkBackticks3 = verifyNot checkBackticks "echo `#inlined comment` foo"-checkBackticks params (T_Backticked id list) | not (null list) =- addComment $- makeCommentWithFix StyleC id 2006 "Use $(...) notation instead of legacy backticks `...`."- (fixWith [replaceStart id params 1 "$(", replaceEnd id params 1 ")"])-checkBackticks _ _ = return ()---prop_checkBadParameterSubstitution1 = verify checkBadParameterSubstitution "${foo$n}"-prop_checkBadParameterSubstitution2 = verifyNot checkBadParameterSubstitution "${foo//$n/lol}"-prop_checkBadParameterSubstitution3 = verify checkBadParameterSubstitution "${$#}"-prop_checkBadParameterSubstitution4 = verify checkBadParameterSubstitution "${var${n}_$((i%2))}"-prop_checkBadParameterSubstitution5 = verifyNot checkBadParameterSubstitution "${bar}"-prop_checkBadParameterSubstitution6 = verify checkBadParameterSubstitution "${\"bar\"}"-prop_checkBadParameterSubstitution7 = verify checkBadParameterSubstitution "${{var}"-prop_checkBadParameterSubstitution8 = verify checkBadParameterSubstitution "${$(x)//x/y}"-prop_checkBadParameterSubstitution9 = verifyNot checkBadParameterSubstitution "$# ${#} $! ${!} ${!#} ${#!}"-prop_checkBadParameterSubstitution10 = verify checkBadParameterSubstitution "${'foo'}"-prop_checkBadParameterSubstitution11 = verify checkBadParameterSubstitution "${${x%.*}##*/}"--checkBadParameterSubstitution _ t =- case t of- (T_DollarBraced i _ (T_NormalWord _ contents@(first:_))) ->- if isIndirection contents- then err i 2082 "To expand via indirection, use arrays, ${!name} or (for sh only) eval."- else checkFirst first- _ -> return ()-- where-- isIndirection vars =- let list = mapMaybe isIndirectionPart vars in- not (null list) && and list-- isIndirectionPart t =- case t of T_DollarExpansion {} -> Just True- T_Backticked {} -> Just True- T_DollarBraced {} -> Just True- T_DollarArithmetic {} -> Just True- T_Literal _ s -> if all isVariableChar s- then Nothing- else Just False- _ -> Just False-- checkFirst t =- case t of- T_Literal id (c:_) ->- if isVariableChar c || isSpecialVariableChar c- then return ()- else err id 2296 $ "Parameter expansions can't start with " ++ e4m [c] ++ ". Double check syntax."-- T_ParamSubSpecialChar {} -> return ()-- T_DoubleQuoted id [T_Literal _ s] | isVariable s ->- err id 2297 "Double quotes must be outside ${}: ${\"invalid\"} vs \"${valid}\"."-- T_DollarBraced id braces _ | isUnmodifiedParameterExpansion t ->- err id 2298 $- (if braces then "${${x}}" else "${$x}")- ++ " is invalid. For expansion, use ${x}. For indirection, use arrays, ${!x} or (for sh) eval."-- T_DollarBraced {} ->- err (getId t) 2299 "Parameter expansions can't be nested. Use temporary variables."-- _ | isCommandSubstitution t ->- err (getId t) 2300 "Parameter expansion can't be applied to command substitutions. Use temporary variables."-- _ -> err (getId t) 2301 $ "Parameter expansion starts with unexpected " ++ name t ++ ". Double check syntax."-- isVariable str =- case str of- [c] -> isVariableStartChar c || isSpecialVariableChar c || isDigit c- x -> isVariableName x-- name t =- case t of- T_SingleQuoted {} -> "quotes"- T_DoubleQuoted {} -> "quotes"- _ -> "syntax"---prop_checkInexplicablyUnquoted1 = verify checkInexplicablyUnquoted "echo 'var='value';'"-prop_checkInexplicablyUnquoted2 = verifyNot checkInexplicablyUnquoted "'foo'*"-prop_checkInexplicablyUnquoted3 = verifyNot checkInexplicablyUnquoted "wget --user-agent='something'"-prop_checkInexplicablyUnquoted4 = verify checkInexplicablyUnquoted "echo \"VALUES (\"id\")\""-prop_checkInexplicablyUnquoted5 = verifyNot checkInexplicablyUnquoted "\"$dir\"/\"$file\""-prop_checkInexplicablyUnquoted6 = verifyNot checkInexplicablyUnquoted "\"$dir\"some_stuff\"$file\""-prop_checkInexplicablyUnquoted7 = verifyNot checkInexplicablyUnquoted "${dir/\"foo\"/\"bar\"}"-prop_checkInexplicablyUnquoted8 = verifyNot checkInexplicablyUnquoted " 'foo'\\\n 'bar'"-prop_checkInexplicablyUnquoted9 = verifyNot checkInexplicablyUnquoted "[[ $x =~ \"foo\"(\"bar\"|\"baz\") ]]"-prop_checkInexplicablyUnquoted10 = verifyNot checkInexplicablyUnquoted "cmd ${x+--name=\"$x\" --output=\"$x.out\"}"-prop_checkInexplicablyUnquoted11 = verifyNot checkInexplicablyUnquoted "echo \"foo\"/\"bar\""-prop_checkInexplicablyUnquoted12 = verifyNot checkInexplicablyUnquoted "declare \"foo\"=\"bar\""-checkInexplicablyUnquoted params (T_NormalWord id tokens) = mapM_ check (tails tokens)- where- check (T_SingleQuoted _ _:T_Literal id str:_)- | not (null str) && all isAlphaNum str =- info id 2026 "This word is outside of quotes. Did you intend to 'nest '\"'single quotes'\"' instead'? "-- check (T_DoubleQuoted _ a:trapped:T_DoubleQuoted _ b:_) =- case trapped of- T_DollarExpansion id _ -> warnAboutExpansion id- T_DollarBraced id _ _ -> warnAboutExpansion id- T_Literal id s- | not (quotesSingleThing a && quotesSingleThing b- || s `elem` ["=", ":", "/"]- || isSpecial (getPath (parentMap params) trapped)- ) ->- warnAboutLiteral id- _ -> return ()-- check _ = return ()-- -- Regexes for [[ .. =~ re ]] are parsed with metacharacters like ()| as unquoted- -- literals. The same is true for ${x+"foo" "bar"}. Avoid overtriggering on these.- isSpecial t =- case t of- (T_Redirecting {} : _) -> False- T_DollarBraced {} : _ -> True- (a:(TC_Binary _ _ "=~" lhs rhs):rest) -> getId a == getId rhs- _:rest -> isSpecial rest- _ -> False-- -- If the surrounding quotes quote single things, like "$foo"_and_then_some_"$stuff",- -- the quotes were probably intentional and harmless.- quotesSingleThing x = case x of- [T_DollarExpansion _ _] -> True- [T_DollarBraced _ _ _] -> True- [T_Backticked _ _] -> True- _ -> False-- warnAboutExpansion id =- warn id 2027 "The surrounding quotes actually unquote this. Remove or escape them."- warnAboutLiteral id =- warn id 2140 "Word is of the form \"A\"B\"C\" (B indicated). Did you mean \"ABC\" or \"A\\\"B\\\"C\"?"-checkInexplicablyUnquoted _ _ = return ()--prop_checkTildeInQuotes1 = verify checkTildeInQuotes "var=\"~/out.txt\""-prop_checkTildeInQuotes2 = verify checkTildeInQuotes "foo > '~/dir'"-prop_checkTildeInQuotes4 = verifyNot checkTildeInQuotes "~/file"-prop_checkTildeInQuotes5 = verifyNot checkTildeInQuotes "echo '/~foo/cow'"-prop_checkTildeInQuotes6 = verifyNot checkTildeInQuotes "awk '$0 ~ /foo/'"-checkTildeInQuotes _ = check- where- verify id ('~':'/':_) = warn id 2088 "Tilde does not expand in quotes. Use $HOME."- verify _ _ = return ()- check (T_NormalWord _ (T_SingleQuoted id str:_)) =- verify id str- check (T_NormalWord _ (T_DoubleQuoted _ (T_Literal id str:_):_)) =- verify id str- check _ = return ()--prop_checkLonelyDotDash1 = verify checkLonelyDotDash "./ file"-prop_checkLonelyDotDash2 = verifyNot checkLonelyDotDash "./file"-checkLonelyDotDash _ t@(T_Redirecting id _ _)- | isUnqualifiedCommand t "./" =- err id 2083 "Don't add spaces after the slash in './file'."-checkLonelyDotDash _ _ = return ()---prop_checkSpuriousExec1 = verify checkSpuriousExec "exec foo; true"-prop_checkSpuriousExec2 = verify checkSpuriousExec "if a; then exec b; exec c; fi"-prop_checkSpuriousExec3 = verifyNot checkSpuriousExec "echo cow; exec foo"-prop_checkSpuriousExec4 = verifyNot checkSpuriousExec "if a; then exec b; fi"-prop_checkSpuriousExec5 = verifyNot checkSpuriousExec "exec > file; cmd"-prop_checkSpuriousExec6 = verify checkSpuriousExec "exec foo > file; cmd"-prop_checkSpuriousExec7 = verifyNot checkSpuriousExec "exec file; echo failed; exit 3"-prop_checkSpuriousExec8 = verifyNot checkSpuriousExec "exec {origout}>&1- >tmp.log 2>&1; bar"-prop_checkSpuriousExec9 = verify checkSpuriousExec "for file in rc.d/*; do exec \"$file\"; done"-prop_checkSpuriousExec10 = verifyNot checkSpuriousExec "exec file; r=$?; printf >&2 'failed\n'; return $r"-prop_checkSpuriousExec11 = verifyNot checkSpuriousExec "exec file; :"-checkSpuriousExec _ = doLists- where- doLists (T_Script _ _ cmds) = doList cmds False- doLists (T_BraceGroup _ cmds) = doList cmds False- doLists (T_WhileExpression _ _ cmds) = doList cmds True- doLists (T_UntilExpression _ _ cmds) = doList cmds True- doLists (T_ForIn _ _ _ cmds) = doList cmds True- doLists (T_ForArithmetic _ _ _ _ cmds) = doList cmds True- doLists (T_IfExpression _ thens elses) = do- mapM_ (\(_, l) -> doList l False) thens- doList elses False- doLists _ = return ()-- stripCleanup = reverse . dropWhile cleanup . reverse- cleanup (T_Pipeline _ _ [cmd]) =- isCommandMatch cmd (`elem` [":", "echo", "exit", "printf", "return"])- || isAssignment cmd- cleanup _ = False-- doList = doList' . stripCleanup- -- The second parameter is True if we are in a loop- -- In that case we should emit the warning also if `exec' is the last statement- doList' (current:t@(following:_)) False = do- commentIfExec current- doList t False- doList' (current:tail) True = do- commentIfExec current- doList tail True- doList' _ _ = return ()-- commentIfExec (T_Pipeline id _ [c]) = commentIfExec c- commentIfExec (T_Redirecting _ _ (T_SimpleCommand id _ (cmd:additionalArg:_))) |- getLiteralString cmd == Just "exec" =- warn id 2093 "Remove \"exec \" if script should continue after this command."- commentIfExec _ = return ()---prop_checkSpuriousExpansion1 = verify checkSpuriousExpansion "if $(true); then true; fi"-prop_checkSpuriousExpansion3 = verifyNot checkSpuriousExpansion "$(cmd) --flag1 --flag2"-prop_checkSpuriousExpansion4 = verify checkSpuriousExpansion "$((i++))"-checkSpuriousExpansion _ (T_SimpleCommand _ _ [T_NormalWord _ [word]]) = check word- where- check word = case word of- T_DollarExpansion id _ ->- warn id 2091 "Remove surrounding $() to avoid executing output (or use eval if intentional)."- T_Backticked id _ ->- warn id 2092 "Remove backticks to avoid executing output (or use eval if intentional)."- T_DollarArithmetic id _ ->- err id 2084 "Remove '$' or use '_=$((expr))' to avoid executing output."- _ -> return ()-checkSpuriousExpansion _ _ = return ()---prop_checkDollarBrackets1 = verify checkDollarBrackets "echo $[1+2]"-prop_checkDollarBrackets2 = verifyNot checkDollarBrackets "echo $((1+2))"-checkDollarBrackets _ (T_DollarBracket id _) =- style id 2007 "Use $((..)) instead of deprecated $[..]"-checkDollarBrackets _ _ = return ()--prop_checkSshHereDoc1 = verify checkSshHereDoc "ssh host << foo\necho $PATH\nfoo"-prop_checkSshHereDoc2 = verifyNot checkSshHereDoc "ssh host << 'foo'\necho $PATH\nfoo"-checkSshHereDoc _ (T_Redirecting _ redirs cmd)- | cmd `isCommand` "ssh" =- mapM_ checkHereDoc redirs- where- hasVariables = mkRegex "[`$]"- checkHereDoc (T_FdRedirect _ _ (T_HereDoc id _ Unquoted token tokens))- | not (all isConstant tokens) =- warn id 2087 $ "Quote '" ++ (e4m token) ++ "' to make here document expansions happen on the server side rather than on the client."- checkHereDoc _ = return ()-checkSshHereDoc _ _ = return ()----- Subshell detection-prop_subshellAssignmentCheck = verifyTree subshellAssignmentCheck "cat foo | while read bar; do a=$bar; done; echo \"$a\""-prop_subshellAssignmentCheck2 = verifyNotTree subshellAssignmentCheck "while read bar; do a=$bar; done < file; echo \"$a\""-prop_subshellAssignmentCheck3 = verifyTree subshellAssignmentCheck "( A=foo; ); rm $A"-prop_subshellAssignmentCheck4 = verifyNotTree subshellAssignmentCheck "( A=foo; rm $A; )"-prop_subshellAssignmentCheck5 = verifyTree subshellAssignmentCheck "cat foo | while read cow; do true; done; echo $cow;"-prop_subshellAssignmentCheck6 = verifyTree subshellAssignmentCheck "( export lol=$(ls); ); echo $lol;"-prop_subshellAssignmentCheck6a = verifyTree subshellAssignmentCheck "( typeset -a lol=a; ); echo $lol;"-prop_subshellAssignmentCheck7 = verifyTree subshellAssignmentCheck "cmd | while read foo; do (( n++ )); done; echo \"$n lines\""-prop_subshellAssignmentCheck8 = verifyTree subshellAssignmentCheck "n=3 & echo $((n++))"-prop_subshellAssignmentCheck9 = verifyTree subshellAssignmentCheck "read n & n=foo$n"-prop_subshellAssignmentCheck10 = verifyTree subshellAssignmentCheck "(( n <<= 3 )) & (( n |= 4 )) &"-prop_subshellAssignmentCheck11 = verifyTree subshellAssignmentCheck "cat /etc/passwd | while read line; do let n=n+1; done\necho $n"-prop_subshellAssignmentCheck12 = verifyTree subshellAssignmentCheck "cat /etc/passwd | while read line; do let ++n; done\necho $n"-prop_subshellAssignmentCheck13 = verifyTree subshellAssignmentCheck "#!/bin/bash\necho foo | read bar; echo $bar"-prop_subshellAssignmentCheck14 = verifyNotTree subshellAssignmentCheck "#!/bin/ksh93\necho foo | read bar; echo $bar"-prop_subshellAssignmentCheck15 = verifyNotTree subshellAssignmentCheck "#!/bin/ksh\ncat foo | while read bar; do a=$bar; done\necho \"$a\""-prop_subshellAssignmentCheck16 = verifyNotTree subshellAssignmentCheck "(set -e); echo $@"-prop_subshellAssignmentCheck17 = verifyNotTree subshellAssignmentCheck "foo=${ { bar=$(baz); } 2>&1; }; echo $foo $bar"-prop_subshellAssignmentCheck18 = verifyTree subshellAssignmentCheck "( exec {n}>&2; ); echo $n"-prop_subshellAssignmentCheck19 = verifyNotTree subshellAssignmentCheck "#!/bin/bash\nshopt -s lastpipe; echo a | read -r b; echo \"$b\""-prop_subshellAssignmentCheck20 = verifyTree subshellAssignmentCheck "@test 'foo' { a=1; }\n@test 'bar' { echo $a; }\n"-prop_subshellAssignmentCheck21 = verifyNotTree subshellAssignmentCheck "test1() { echo foo | if [[ $var ]]; then echo $var; fi; }; test2() { echo $var; }"-prop_subshellAssignmentCheck22 = verifyNotTree subshellAssignmentCheck "( [[ -n $foo || -z $bar ]] ); echo $foo $bar"-prop_subshellAssignmentCheck23 = verifyNotTree subshellAssignmentCheck "( export foo ); echo $foo"-subshellAssignmentCheck params t =- let flow = variableFlow params- check = findSubshelled flow [("oops",[])] Map.empty- in execWriter check---findSubshelled [] _ _ = return ()-findSubshelled (Assignment x@(_, _, str, data_):rest) scopes@((reason,scope):restscope) deadVars =- if isTrueAssignmentSource data_- then findSubshelled rest ((reason, x:scope):restscope) $ Map.insert str Alive deadVars- else findSubshelled rest scopes deadVars--findSubshelled (Reference (_, readToken, str):rest) scopes deadVars = do- unless (shouldIgnore str) $ case Map.findWithDefault Alive str deadVars of- Alive -> return ()- Dead writeToken reason -> do- info (getId writeToken) 2030 $ "Modification of " ++ str ++ " is local (to subshell caused by "++ reason ++")."- info (getId readToken) 2031 $ str ++ " was modified in a subshell. That change might be lost."- findSubshelled rest scopes deadVars- where- shouldIgnore str =- str `elem` ["@", "*", "IFS"]--findSubshelled (StackScope (SubshellScope reason):rest) scopes deadVars =- findSubshelled rest ((reason,[]):scopes) deadVars--findSubshelled (StackScopeEnd:rest) ((reason, scope):oldScopes) deadVars =- findSubshelled rest oldScopes $- foldl (\m (_, token, var, _) ->- Map.insert var (Dead token reason) m) deadVars scope----- FIXME: This is a very strange way of doing it.--- For each variable read/write, run a stateful function that emits--- comments. The comments are collected and returned.-doVariableFlowAnalysis ::- (Token -> Token -> String -> State t [v])- -> (Token -> Token -> String -> DataType -> State t [v])- -> t- -> [StackData]- -> [v]--doVariableFlowAnalysis readFunc writeFunc empty flow = evalState (- foldM (\list x -> do { l <- doFlow x; return $ l ++ list; }) [] flow- ) empty- where- doFlow (Reference (base, token, name)) =- readFunc base token name- doFlow (Assignment (base, token, name, values)) =- writeFunc base token name values- doFlow _ = return []---- Don't suggest quotes if this will instead be autocorrected--- from $foo=bar to foo=bar. This is not pretty but ok.-quotesMayConflictWithSC2281 params t =- case getPath (parentMap params) t of- _ : T_NormalWord parentId (me:T_Literal _ ('=':_):_) : T_SimpleCommand _ _ (cmd:_) : _ ->- (getId t) == (getId me) && (parentId == getId cmd)- _ -> False--addDoubleQuotesAround params token = (surroundWith (getId token) params "\"")--prop_checkSpacefulnessCfg1 = verify checkSpacefulnessCfg "a='cow moo'; echo $a"-prop_checkSpacefulnessCfg2 = verifyNot checkSpacefulnessCfg "a='cow moo'; [[ $a ]]"-prop_checkSpacefulnessCfg3 = verifyNot checkSpacefulnessCfg "a='cow*.mp3'; echo \"$a\""-prop_checkSpacefulnessCfg4 = verify checkSpacefulnessCfg "for f in *.mp3; do echo $f; done"-prop_checkSpacefulnessCfg4a = verifyNot checkSpacefulnessCfg "foo=3; foo=$(echo $foo)"-prop_checkSpacefulnessCfg5 = verify checkSpacefulnessCfg "a='*'; b=$a; c=lol${b//foo/bar}; echo $c"-prop_checkSpacefulnessCfg6 = verify checkSpacefulnessCfg "a=foo$(lol); echo $a"-prop_checkSpacefulnessCfg7 = verify checkSpacefulnessCfg "a=foo\\ bar; rm $a"-prop_checkSpacefulnessCfg8 = verifyNot checkSpacefulnessCfg "a=foo\\ bar; a=foo; rm $a"-prop_checkSpacefulnessCfg10 = verify checkSpacefulnessCfg "rm $1"-prop_checkSpacefulnessCfg11 = verify checkSpacefulnessCfg "rm ${10//foo/bar}"-prop_checkSpacefulnessCfg12 = verifyNot checkSpacefulnessCfg "(( $1 + 3 ))"-prop_checkSpacefulnessCfg13 = verifyNot checkSpacefulnessCfg "if [[ $2 -gt 14 ]]; then true; fi"-prop_checkSpacefulnessCfg14 = verifyNot checkSpacefulnessCfg "foo=$3 env"-prop_checkSpacefulnessCfg15 = verifyNot checkSpacefulnessCfg "local foo=$1"-prop_checkSpacefulnessCfg16 = verifyNot checkSpacefulnessCfg "declare foo=$1"-prop_checkSpacefulnessCfg17 = verify checkSpacefulnessCfg "echo foo=$1"-prop_checkSpacefulnessCfg18 = verifyNot checkSpacefulnessCfg "$1 --flags"-prop_checkSpacefulnessCfg19 = verify checkSpacefulnessCfg "echo $PWD"-prop_checkSpacefulnessCfg20 = verifyNot checkSpacefulnessCfg "n+='foo bar'"-prop_checkSpacefulnessCfg21 = verifyNot checkSpacefulnessCfg "select foo in $bar; do true; done"-prop_checkSpacefulnessCfg22 = verifyNot checkSpacefulnessCfg "echo $\"$1\""-prop_checkSpacefulnessCfg23 = verifyNot checkSpacefulnessCfg "a=(1); echo ${a[@]}"-prop_checkSpacefulnessCfg24 = verify checkSpacefulnessCfg "a='a b'; cat <<< $a"-prop_checkSpacefulnessCfg25 = verify checkSpacefulnessCfg "a='s/[0-9]//g'; sed $a"-prop_checkSpacefulnessCfg26 = verify checkSpacefulnessCfg "a='foo bar'; echo {1,2,$a}"-prop_checkSpacefulnessCfg27 = verifyNot checkSpacefulnessCfg "echo ${a:+'foo'}"-prop_checkSpacefulnessCfg28 = verifyNot checkSpacefulnessCfg "exec {n}>&1; echo $n"-prop_checkSpacefulnessCfg29 = verifyNot checkSpacefulnessCfg "n=$(stuff); exec {n}>&-;"-prop_checkSpacefulnessCfg30 = verify checkSpacefulnessCfg "file='foo bar'; echo foo > $file;"-prop_checkSpacefulnessCfg31 = verifyNot checkSpacefulnessCfg "echo \"`echo \\\"$1\\\"`\""-prop_checkSpacefulnessCfg32 = verifyNot checkSpacefulnessCfg "var=$1; [ -v var ]"-prop_checkSpacefulnessCfg33 = verify checkSpacefulnessCfg "for file; do echo $file; done"-prop_checkSpacefulnessCfg34 = verify checkSpacefulnessCfg "declare foo$n=$1"-prop_checkSpacefulnessCfg35 = verifyNot checkSpacefulnessCfg "echo ${1+\"$1\"}"-prop_checkSpacefulnessCfg36 = verifyNot checkSpacefulnessCfg "arg=$#; echo $arg"-prop_checkSpacefulnessCfg37 = verifyNot checkSpacefulnessCfg "@test 'status' {\n [ $status -eq 0 ]\n}"-prop_checkSpacefulnessCfg37v = verify checkVerboseSpacefulnessCfg "@test 'status' {\n [ $status -eq 0 ]\n}"-prop_checkSpacefulnessCfg38 = verify checkSpacefulnessCfg "a=; echo $a"-prop_checkSpacefulnessCfg39 = verifyNot checkSpacefulnessCfg "a=''\"\"''; b=x$a; echo $b"-prop_checkSpacefulnessCfg40 = verifyNot checkSpacefulnessCfg "a=$((x+1)); echo $a"-prop_checkSpacefulnessCfg41 = verifyNot checkSpacefulnessCfg "exec $1 --flags"-prop_checkSpacefulnessCfg42 = verifyNot checkSpacefulnessCfg "run $1 --flags"-prop_checkSpacefulnessCfg43 = verifyNot checkSpacefulnessCfg "$foo=42"-prop_checkSpacefulnessCfg44 = verify checkSpacefulnessCfg "#!/bin/sh\nexport var=$value"-prop_checkSpacefulnessCfg45 = verifyNot checkSpacefulnessCfg "wait -zzx -p foo; echo $foo"-prop_checkSpacefulnessCfg46 = verifyNot checkSpacefulnessCfg "x=0; (( x += 1 )); echo $x"-prop_checkSpacefulnessCfg47 = verifyNot checkSpacefulnessCfg "x=0; (( x-- )); echo $x"-prop_checkSpacefulnessCfg48 = verifyNot checkSpacefulnessCfg "x=0; (( ++x )); echo $x"-prop_checkSpacefulnessCfg49 = verifyNot checkSpacefulnessCfg "for i in 1 2 3; do echo $i; done"-prop_checkSpacefulnessCfg50 = verify checkSpacefulnessCfg "for i in 1 2 *; do echo $i; done"-prop_checkSpacefulnessCfg51 = verify checkSpacefulnessCfg "x='foo bar'; x && x=1; echo $x"-prop_checkSpacefulnessCfg52 = verifyNot checkSpacefulnessCfg "x=1; if f; then x='foo bar'; exit; fi; echo $x"-prop_checkSpacefulnessCfg53 = verifyNot checkSpacefulnessCfg "s=1; f() { local s='a b'; }; f; echo $s"-prop_checkSpacefulnessCfg54 = verifyNot checkSpacefulnessCfg "s='a b'; f() { s=1; }; f; echo $s"-prop_checkSpacefulnessCfg55 = verify checkSpacefulnessCfg "s='a b'; x && f() { s=1; }; f; echo $s"-prop_checkSpacefulnessCfg56 = verifyNot checkSpacefulnessCfg "s=1; cat <(s='a b'); echo $s"-prop_checkSpacefulnessCfg57 = verifyNot checkSpacefulnessCfg "declare -i s=0; s=$(f); echo $s"-prop_checkSpacefulnessCfg58 = verify checkSpacefulnessCfg "f() { declare -i s; }; f; s=$(var); echo $s"-prop_checkSpacefulnessCfg59 = verifyNot checkSpacefulnessCfg "f() { declare -gi s; }; f; s=$(var); echo $s"-prop_checkSpacefulnessCfg60 = verify checkSpacefulnessCfg "declare -i s; declare +i s; s=$(foo); echo $s"-prop_checkSpacefulnessCfg61 = verify checkSpacefulnessCfg "declare -x X; y=foo$X; echo $y;"-prop_checkSpacefulnessCfg62 = verifyNot checkSpacefulnessCfg "f() { declare -x X; y=foo$X; echo $y; }"-prop_checkSpacefulnessCfg63 = verify checkSpacefulnessCfg "f && declare -i s; s='x + y'; echo $s"-prop_checkSpacefulnessCfg64 = verifyNot checkSpacefulnessCfg "declare -i s; s='x + y'; x=$s; echo $x"-prop_checkSpacefulnessCfg65 = verifyNot checkSpacefulnessCfg "f() { s=$?; echo $s; }; f"-prop_checkSpacefulnessCfg66 = verifyNot checkSpacefulnessCfg "f() { s=$?; echo $s; }"--checkSpacefulnessCfg = checkSpacefulnessCfg' True-checkVerboseSpacefulnessCfg = checkSpacefulnessCfg' False--checkSpacefulnessCfg' :: Bool -> (Parameters -> Token -> Writer [TokenComment] ())-checkSpacefulnessCfg' dirtyPass params token@(T_DollarBraced id _ list) =- when (needsQuoting && (dirtyPass == not isClean)) $- unless (name `elem` specialVariablesWithoutSpaces || quotesMayConflictWithSC2281 params token) $- if dirtyPass- then- if isDefaultAssignment (parentMap params) token- then- info (getId token) 2223- "This default assignment may cause DoS due to globbing. Quote it."- else- infoWithFix id 2086 "Double quote to prevent globbing and word splitting." $- addDoubleQuotesAround params token- else- styleWithFix id 2248 "Prefer double quoting even when variables don't contain special characters." $- addDoubleQuotesAround params token-- where- name = getBracedReference $ concat $ oversimplify list- parents = parentMap params- needsQuoting =- not (isArrayExpansion token) -- There's another warning for this- && not (isCountingReference token)- && not (isQuoteFree (shellType params) parents token)- && not (isQuotedAlternativeReference token)- && not (usedAsCommandName parents token)-- isClean = fromMaybe False $ do- state <- CF.getIncomingState (cfgAnalysis params) id- value <- Map.lookup name $ CF.variablesInScope state- return $ isCleanState value-- isCleanState state =- (all (S.member CFVPInteger) $ CF.variableProperties state)- || CF.spaceStatus (CF.variableValue state) == CF.SpaceStatusClean-- isDefaultAssignment parents token =- let modifier = getBracedModifier $ bracedString token in- any (`isPrefixOf` modifier) ["=", ":="]- && isParamTo parents ":" token-- -- Given a T_DollarBraced, return a simplified version of the string contents.- bracedString (T_DollarBraced _ _ l) = concat $ oversimplify l- bracedString _ = error $ pleaseReport "bracedString on non-variable"--checkSpacefulnessCfg' _ _ _ = return ()---prop_CheckVariableBraces1 = verify checkVariableBraces "a='123'; echo $a"-prop_CheckVariableBraces2 = verifyNot checkVariableBraces "a='123'; echo ${a}"-prop_CheckVariableBraces3 = verifyNot checkVariableBraces "#shellcheck disable=SC2016\necho '$a'"-prop_CheckVariableBraces4 = verifyNot checkVariableBraces "echo $* $1"-prop_CheckVariableBraces5 = verifyNot checkVariableBraces "$foo=42"-checkVariableBraces params t@(T_DollarBraced id False l)- | name `notElem` unbracedVariables && not (quotesMayConflictWithSC2281 params t) =- styleWithFix id 2250- "Prefer putting braces around variable references even when not strictly required."- (fixFor t)- where- name = getBracedReference $ concat $ oversimplify l- fixFor token = fixWith [replaceStart (getId token) params 1 "${"- ,replaceEnd (getId token) params 0 "}"]-checkVariableBraces _ _ = return ()--prop_checkQuotesInLiterals1 = verifyTree checkQuotesInLiterals "param='--foo=\"bar\"'; app $param"-prop_checkQuotesInLiterals1a = verifyTree checkQuotesInLiterals "param=\"--foo='lolbar'\"; app $param"-prop_checkQuotesInLiterals2 = verifyNotTree checkQuotesInLiterals "param='--foo=\"bar\"'; app \"$param\""-prop_checkQuotesInLiterals3 =verifyNotTree checkQuotesInLiterals "param=('--foo='); app \"${param[@]}\""-prop_checkQuotesInLiterals4 = verifyNotTree checkQuotesInLiterals "param=\"don't bother with this one\"; app $param"-prop_checkQuotesInLiterals5 = verifyNotTree checkQuotesInLiterals "param=\"--foo='lolbar'\"; eval app $param"-prop_checkQuotesInLiterals6 = verifyTree checkQuotesInLiterals "param='my\\ file'; cmd=\"rm $param\"; $cmd"-prop_checkQuotesInLiterals6a = verifyNotTree checkQuotesInLiterals "param='my\\ file'; cmd=\"rm ${#param}\"; $cmd"-prop_checkQuotesInLiterals7 = verifyTree checkQuotesInLiterals "param='my\\ file'; rm $param"-prop_checkQuotesInLiterals8 = verifyTree checkQuotesInLiterals "param=\"/foo/'bar baz'/etc\"; rm $param"-prop_checkQuotesInLiterals9 = verifyNotTree checkQuotesInLiterals "param=\"/foo/'bar baz'/etc\"; rm ${#param}"-checkQuotesInLiterals params t =- doVariableFlowAnalysis readF writeF Map.empty (variableFlow params)- where- getQuotes name = gets (Map.lookup name)- setQuotes name ref = modify $ Map.insert name ref- deleteQuotes = modify . Map.delete- parents = parentMap params- quoteRegex = mkRegex "\"|([/= ]|^)'|'( |$)|\\\\ "- containsQuotes s = s `matches` quoteRegex-- writeF _ _ name (DataString (SourceFrom values)) = do- quoteMap <- get- let quotedVars = msum $ map (forToken quoteMap) values- case quotedVars of- Nothing -> deleteQuotes name- Just x -> setQuotes name x- return []- writeF _ _ _ _ = return []-- forToken map (T_DollarBraced id _ t) =- -- skip getBracedReference here to avoid false positives on PE- Map.lookup (concat . oversimplify $ t) map- forToken quoteMap (T_DoubleQuoted id tokens) =- msum $ map (forToken quoteMap) tokens- forToken quoteMap (T_NormalWord id tokens) =- msum $ map (forToken quoteMap) tokens- forToken _ t =- if containsQuotes (concat $ oversimplify t)- then return $ getId t- else Nothing-- squashesQuotes t =- case t of- T_DollarBraced id _ l -> "#" `isPrefixOf` concat (oversimplify l)- _ -> False-- readF _ expr name = do- assignment <- getQuotes name- return $ case assignment of- Just j- | not (isParamTo parents "eval" expr)- && not (isQuoteFree (shellType params) parents expr)- && not (squashesQuotes expr)- -> [- makeComment WarningC j 2089 $- "Quotes/backslashes will be treated literally. " ++ suggestion,- makeComment WarningC (getId expr) 2090- "Quotes/backslashes in this variable will not be respected."- ]- _ -> []- suggestion =- if supportsArrays (shellType params)- then "Use an array."- else "Rewrite using set/\"$@\" or functions."---prop_checkFunctionsUsedExternally1 =- verifyTree checkFunctionsUsedExternally "foo() { :; }; sudo foo"-prop_checkFunctionsUsedExternally2 =- verifyTree checkFunctionsUsedExternally "alias f='a'; xargs -0 f"-prop_checkFunctionsUsedExternally2b =- verifyNotTree checkFunctionsUsedExternally "alias f='a'; find . -type f"-prop_checkFunctionsUsedExternally2c =- verifyTree checkFunctionsUsedExternally "alias f='a'; find . -type f -exec f +"-prop_checkFunctionsUsedExternally3 =- verifyNotTree checkFunctionsUsedExternally "f() { :; }; echo f"-prop_checkFunctionsUsedExternally4 =- verifyNotTree checkFunctionsUsedExternally "foo() { :; }; sudo \"foo\""-prop_checkFunctionsUsedExternally5 =- verifyTree checkFunctionsUsedExternally "foo() { :; }; ssh host foo"-prop_checkFunctionsUsedExternally6 =- verifyNotTree checkFunctionsUsedExternally "foo() { :; }; ssh host echo foo"-prop_checkFunctionsUsedExternally7 =- verifyNotTree checkFunctionsUsedExternally "install() { :; }; sudo apt-get install foo"-prop_checkFunctionsUsedExternally8 =- verifyTree checkFunctionsUsedExternally "foo() { :; }; command sudo foo"-prop_checkFunctionsUsedExternally9 =- verifyTree checkFunctionsUsedExternally "foo() { :; }; exec -c sudo foo"-checkFunctionsUsedExternally params t =- runNodeAnalysis checkCommand params t- where- checkCommand _ t@(T_SimpleCommand _ _ argv) =- case getCommandNameAndToken False t of- (Just str, t) -> do- let name = basename str- let args = skipOver t argv- let argStrings = map (\x -> (fromMaybe "" $ getLiteralString x, x)) args- let candidates = getPotentialCommands name argStrings- mapM_ (checkArg name (getId t)) candidates- _ -> return ()- checkCommand _ _ = return ()-- skipOver t list = drop 1 $ dropWhile (\c -> getId c /= id) $ list- where id = getId t-- -- Try to pick out the argument[s] that may be commands- getPotentialCommands name argAndString =- case name of- "chroot" -> firstNonFlag- "screen" -> firstNonFlag- "sudo" -> firstNonFlag- "xargs" -> firstNonFlag- "tmux" -> firstNonFlag- "ssh" -> take 1 $ drop 1 $ dropFlags argAndString- "find" -> take 1 $ drop 1 $- dropWhile (\x -> fst x `notElem` findExecFlags) argAndString- _ -> []- where- firstNonFlag = take 1 $ dropFlags argAndString- findExecFlags = ["-exec", "-execdir", "-ok"]- dropFlags = dropWhile (\x -> "-" `isPrefixOf` fst x)-- functionsAndAliases = Map.union (functions t) (aliases t)-- patternContext id =- case posLine . fst <$> Map.lookup id (tokenPositions params) of- Just l -> " on line " <> show l <> "."- _ -> "."-- checkArg cmd cmdId (_, arg) = sequence_ $ do- literalArg <- getUnquotedLiteral arg -- only consider unquoted literals- definitionId <- Map.lookup literalArg functionsAndAliases- return $ do- warn (getId arg) 2033- "Shell functions can't be passed to external commands. Use separate script or sh -c."- info definitionId 2032 $- "This function can't be invoked via " ++ cmd ++ patternContext cmdId--prop_checkUnused0 = verifyNotTree checkUnusedAssignments "var=foo; echo $var"-prop_checkUnused1 = verifyTree checkUnusedAssignments "var=foo; echo $bar"-prop_checkUnused2 = verifyNotTree checkUnusedAssignments "var=foo; export var;"-prop_checkUnused3 = verifyTree checkUnusedAssignments "for f in *; do echo '$f'; done"-prop_checkUnused4 = verifyTree checkUnusedAssignments "local i=0"-prop_checkUnused5 = verifyNotTree checkUnusedAssignments "read lol; echo $lol"-prop_checkUnused6 = verifyNotTree checkUnusedAssignments "var=4; (( var++ ))"-prop_checkUnused7 = verifyNotTree checkUnusedAssignments "var=2; $((var))"-prop_checkUnused8 = verifyTree checkUnusedAssignments "var=2; var=3;"-prop_checkUnused9 = verifyNotTree checkUnusedAssignments "read ''"-prop_checkUnused10 = verifyNotTree checkUnusedAssignments "read -p 'test: '"-prop_checkUnused11 = verifyNotTree checkUnusedAssignments "bar=5; export foo[$bar]=3"-prop_checkUnused12 = verifyNotTree checkUnusedAssignments "read foo; echo ${!foo}"-prop_checkUnused13 = verifyNotTree checkUnusedAssignments "x=(1); (( x[0] ))"-prop_checkUnused14 = verifyNotTree checkUnusedAssignments "x=(1); n=0; echo ${x[n]}"-prop_checkUnused15 = verifyNotTree checkUnusedAssignments "x=(1); n=0; (( x[n] ))"-prop_checkUnused16 = verifyNotTree checkUnusedAssignments "foo=5; declare -x foo"-prop_checkUnused16b = verifyNotTree checkUnusedAssignments "f() { local -x foo; foo=42; bar; }; f"-prop_checkUnused17 = verifyNotTree checkUnusedAssignments "read -i 'foo' -e -p 'Input: ' bar; $bar;"-prop_checkUnused18 = verifyNotTree checkUnusedAssignments "a=1; arr=( [$a]=42 ); echo \"${arr[@]}\""-prop_checkUnused19 = verifyNotTree checkUnusedAssignments "a=1; let b=a+1; echo $b"-prop_checkUnused20 = verifyNotTree checkUnusedAssignments "a=1; PS1='$a'"-prop_checkUnused21 = verifyNotTree checkUnusedAssignments "a=1; trap 'echo $a' INT"-prop_checkUnused22 = verifyNotTree checkUnusedAssignments "a=1; [ -v a ]"-prop_checkUnused23 = verifyNotTree checkUnusedAssignments "a=1; [ -R a ]"-prop_checkUnused24 = verifyNotTree checkUnusedAssignments "mapfile -C a b; echo ${b[@]}"-prop_checkUnused25 = verifyNotTree checkUnusedAssignments "readarray foo; echo ${foo[@]}"-prop_checkUnused26 = verifyNotTree checkUnusedAssignments "declare -F foo"-prop_checkUnused27 = verifyTree checkUnusedAssignments "var=3; [ var -eq 3 ]"-prop_checkUnused28 = verifyNotTree checkUnusedAssignments "var=3; [[ var -eq 3 ]]"-prop_checkUnused29 = verifyNotTree checkUnusedAssignments "var=(a b); declare -p var"-prop_checkUnused30 = verifyTree checkUnusedAssignments "let a=1"-prop_checkUnused31 = verifyTree checkUnusedAssignments "let 'a=1'"-prop_checkUnused32 = verifyTree checkUnusedAssignments "let a=b=c; echo $a"-prop_checkUnused33 = verifyNotTree checkUnusedAssignments "a=foo; [[ foo =~ ^{$a}$ ]]"-prop_checkUnused34 = verifyNotTree checkUnusedAssignments "foo=1; (( t = foo )); echo $t"-prop_checkUnused35 = verifyNotTree checkUnusedAssignments "a=foo; b=2; echo ${a:b}"-prop_checkUnused36 = verifyNotTree checkUnusedAssignments "if [[ -v foo ]]; then true; fi"-prop_checkUnused37 = verifyNotTree checkUnusedAssignments "fd=2; exec {fd}>&-"-prop_checkUnused38 = verifyTree checkUnusedAssignments "(( a=42 ))"-prop_checkUnused39 = verifyNotTree checkUnusedAssignments "declare -x -f foo"-prop_checkUnused40 = verifyNotTree checkUnusedAssignments "arr=(1 2); num=2; echo \"${arr[@]:num}\""-prop_checkUnused41 = verifyNotTree checkUnusedAssignments "@test 'foo' {\ntrue\n}\n"-prop_checkUnused42 = verifyNotTree checkUnusedAssignments "DEFINE_string foo '' ''; echo \"${FLAGS_foo}\""-prop_checkUnused43 = verifyTree checkUnusedAssignments "DEFINE_string foo '' ''"-prop_checkUnused44 = verifyNotTree checkUnusedAssignments "DEFINE_string \"foo$ibar\" x y"-prop_checkUnused45 = verifyTree checkUnusedAssignments "readonly foo=bar"-prop_checkUnused46 = verifyTree checkUnusedAssignments "readonly foo=(bar)"-prop_checkUnused47 = verifyNotTree checkUnusedAssignments "a=1; alias hello='echo $a'"-prop_checkUnused48 = verifyNotTree checkUnusedAssignments "_a=1"-prop_checkUnused49 = verifyNotTree checkUnusedAssignments "declare -A array; key=a; [[ -v array[$key] ]]"-prop_checkUnused50 = verifyNotTree checkUnusedAssignments "foofunc() { :; }; typeset -fx foofunc"-prop_checkUnused51 = verifyTree checkUnusedAssignments "x[y[z=1]]=1; echo ${x[@]}"--checkUnusedAssignments params t = execWriter (mapM_ warnFor unused)- where- flow = variableFlow params- references = foldl (flip ($)) defaultMap (map insertRef flow)- insertRef (Reference (base, token, name)) =- Map.insert (stripSuffix name) ()- insertRef _ = id-- assignments = foldl (flip ($)) Map.empty (map insertAssignment flow)- insertAssignment (Assignment (_, token, name, _)) | isVariableName name =- Map.insert name token- insertAssignment _ = id-- unused = Map.assocs $ Map.difference assignments references-- warnFor (name, token) =- unless ("_" `isPrefixOf` name) $- warn (getId token) 2034 $- name ++ " appears unused. Verify use (or export if used externally)."-- stripSuffix = takeWhile isVariableChar- defaultMap = Map.fromList $ zip internalVariables $ repeat ()--prop_checkUnassignedReferences1 = verifyTree checkUnassignedReferences "echo $foo"-prop_checkUnassignedReferences2 = verifyNotTree checkUnassignedReferences "foo=hello; echo $foo"-prop_checkUnassignedReferences3 = verifyTree checkUnassignedReferences "MY_VALUE=3; echo $MYVALUE"-prop_checkUnassignedReferences4 = verifyNotTree checkUnassignedReferences "RANDOM2=foo; echo $RANDOM"-prop_checkUnassignedReferences5 = verifyNotTree checkUnassignedReferences "declare -A foo=([bar]=baz); echo ${foo[bar]}"-prop_checkUnassignedReferences6 = verifyNotTree checkUnassignedReferences "foo=..; echo ${foo-bar}"-prop_checkUnassignedReferences7 = verifyNotTree checkUnassignedReferences "getopts ':h' foo; echo $foo"-prop_checkUnassignedReferences8 = verifyNotTree checkUnassignedReferences "let 'foo = 1'; echo $foo"-prop_checkUnassignedReferences9 = verifyNotTree checkUnassignedReferences "echo ${foo-bar}"-prop_checkUnassignedReferences10 = verifyNotTree checkUnassignedReferences "echo ${foo:?}"-prop_checkUnassignedReferences11 = verifyNotTree checkUnassignedReferences "declare -A foo; echo \"${foo[@]}\""-prop_checkUnassignedReferences12 = verifyNotTree checkUnassignedReferences "typeset -a foo; echo \"${foo[@]}\""-prop_checkUnassignedReferences13 = verifyNotTree checkUnassignedReferences "f() { local foo; echo $foo; }"-prop_checkUnassignedReferences14 = verifyNotTree checkUnassignedReferences "foo=; echo $foo"-prop_checkUnassignedReferences15 = verifyNotTree checkUnassignedReferences "f() { true; }; export -f f"-prop_checkUnassignedReferences16 = verifyNotTree checkUnassignedReferences "declare -A foo=( [a b]=bar ); echo ${foo[a b]}"-prop_checkUnassignedReferences17 = verifyNotTree checkUnassignedReferences "USERS=foo; echo $USER"-prop_checkUnassignedReferences18 = verifyNotTree checkUnassignedReferences "FOOBAR=42; export FOOBAR="-prop_checkUnassignedReferences19 = verifyNotTree checkUnassignedReferences "readonly foo=bar; echo $foo"-prop_checkUnassignedReferences20 = verifyNotTree checkUnassignedReferences "printf -v foo bar; echo $foo"-prop_checkUnassignedReferences21 = verifyTree checkUnassignedReferences "echo ${#foo}"-prop_checkUnassignedReferences22 = verifyNotTree checkUnassignedReferences "echo ${!os*}"-prop_checkUnassignedReferences23 = verifyTree checkUnassignedReferences "declare -a foo; foo[bar]=42;"-prop_checkUnassignedReferences24 = verifyNotTree checkUnassignedReferences "declare -A foo; foo[bar]=42;"-prop_checkUnassignedReferences25 = verifyNotTree checkUnassignedReferences "declare -A foo=(); foo[bar]=42;"-prop_checkUnassignedReferences26 = verifyNotTree checkUnassignedReferences "a::b() { foo; }; readonly -f a::b"-prop_checkUnassignedReferences27 = verifyNotTree checkUnassignedReferences ": ${foo:=bar}"-prop_checkUnassignedReferences28 = verifyNotTree checkUnassignedReferences "#!/bin/ksh\necho \"${.sh.version}\"\n"-prop_checkUnassignedReferences29 = verifyNotTree checkUnassignedReferences "if [[ -v foo ]]; then echo $foo; fi"-prop_checkUnassignedReferences30 = verifyNotTree checkUnassignedReferences "if [[ -v foo[3] ]]; then echo ${foo[3]}; fi"-prop_checkUnassignedReferences31 = verifyNotTree checkUnassignedReferences "X=1; if [[ -v foo[$X+42] ]]; then echo ${foo[$X+42]}; fi"-prop_checkUnassignedReferences32 = verifyNotTree checkUnassignedReferences "if [[ -v \"foo[1]\" ]]; then echo ${foo[@]}; fi"-prop_checkUnassignedReferences33 = verifyNotTree checkUnassignedReferences "f() { local -A foo; echo \"${foo[@]}\"; }"-prop_checkUnassignedReferences34 = verifyNotTree checkUnassignedReferences "declare -A foo; (( foo[bar] ))"-prop_checkUnassignedReferences35 = verifyNotTree checkUnassignedReferences "echo ${arr[foo-bar]:?fail}"-prop_checkUnassignedReferences36 = verifyNotTree checkUnassignedReferences "read -a foo -r <<<\"foo bar\"; echo \"$foo\""-prop_checkUnassignedReferences37 = verifyNotTree checkUnassignedReferences "var=howdy; printf -v 'array[0]' %s \"$var\"; printf %s \"${array[0]}\";"-prop_checkUnassignedReferences38 = verifyTree (checkUnassignedReferences' True) "echo $VAR"-prop_checkUnassignedReferences39 = verifyNotTree checkUnassignedReferences "builtin export var=4; echo $var"-prop_checkUnassignedReferences40 = verifyNotTree checkUnassignedReferences ": ${foo=bar}"-prop_checkUnassignedReferences41 = verifyNotTree checkUnassignedReferences "mapfile -t files 123; echo \"${files[@]}\""-prop_checkUnassignedReferences42 = verifyNotTree checkUnassignedReferences "mapfile files -t; echo \"${files[@]}\""-prop_checkUnassignedReferences43 = verifyNotTree checkUnassignedReferences "mapfile --future files; echo \"${files[@]}\""-prop_checkUnassignedReferences_minusNPlain = verifyNotTree checkUnassignedReferences "if [ -n \"$x\" ]; then echo $x; fi"-prop_checkUnassignedReferences_minusZPlain = verifyNotTree checkUnassignedReferences "if [ -z \"$x\" ]; then echo \"\"; fi"-prop_checkUnassignedReferences_minusNBraced = verifyNotTree checkUnassignedReferences "if [ -n \"${x}\" ]; then echo $x; fi"-prop_checkUnassignedReferences_minusZBraced = verifyNotTree checkUnassignedReferences "if [ -z \"${x}\" ]; then echo \"\"; fi"-prop_checkUnassignedReferences_minusNDefault = verifyNotTree checkUnassignedReferences "if [ -n \"${x:-}\" ]; then echo $x; fi"-prop_checkUnassignedReferences_minusZDefault = verifyNotTree checkUnassignedReferences "if [ -z \"${x:-}\" ]; then echo \"\"; fi"-prop_checkUnassignedReferences50 = verifyNotTree checkUnassignedReferences "echo ${foo:+bar}"-prop_checkUnassignedReferences51 = verifyNotTree checkUnassignedReferences "echo ${foo:+$foo}"-prop_checkUnassignedReferences52 = verifyNotTree checkUnassignedReferences "wait -p pid; echo $pid"--checkUnassignedReferences = checkUnassignedReferences' False-checkUnassignedReferences' includeGlobals params t = warnings- where- (readMap, writeMap) = execState (mapM tally $ variableFlow params) (Map.empty, Map.empty)- defaultAssigned = Map.fromList $ map (\a -> (a, ())) $ filter (not . null) internalVariables-- tally (Assignment (_, _, name, _)) =- modify (\(read, written) -> (read, Map.insert name () written))- tally (Reference (_, place, name)) =- modify (\(read, written) -> (Map.insertWith (const id) name place read, written))- tally _ = return ()-- unassigned = Map.toList $ Map.difference (Map.difference readMap writeMap) defaultAssigned- writtenVars = filter isVariableName $ Map.keys writeMap-- getBestMatch var = do- (match, score) <- listToMaybe best- guard $ goodMatch var match score- return match- where- matches = map (\x -> (x, match var x)) writtenVars- best = sortBy (comparing snd) matches- goodMatch var match score =- let l = length match in- l > 3 && score <= 1- || l > 7 && score <= 2-- isLocal = any isLower-- warningForGlobals var place = do- match <- getBestMatch var- return $ info (getId place) 2153 $- "Possible misspelling: " ++ var ++ " may not be assigned. Did you mean " ++ match ++ "?"-- warningForLocals var place =- return $ warn (getId place) 2154 $- var ++ " is referenced but not assigned" ++ optionalTip ++ "."- where- optionalTip =- if var `elem` commonCommands- then " (for output from commands, use \"$(" ++ var ++ " ..." ++ ")\" )"- else fromMaybe "" $ do- match <- getBestMatch var- return $ " (did you mean '" ++ match ++ "'?)"-- warningFor (var, place) = do- guard $ isVariableName var- guard . not $ isException var place || isGuarded place- (if includeGlobals || isLocal var- then warningForLocals- else warningForGlobals) var place-- warnings = execWriter . sequence $ mapMaybe warningFor unassigned-- -- Due to parsing, foo=( [bar]=baz ) parses 'bar' as a reference even for assoc arrays.- -- Similarly, ${foo[bar baz]} may not be referencing bar/baz. Just skip these.- -- We can also have ${foo:+$foo} should be treated like [[ -n $foo ]] && echo $foo- isException var t = any shouldExclude $ getPath (parentMap params) t- where- shouldExclude t =- case t of- T_Array {} -> True- (T_DollarBraced _ _ l) ->- let str = concat $ oversimplify l- ref = getBracedReference str- mod = getBracedModifier str- in- -- Either we're used as an array index like ${arr[here]}- ref /= var ||- -- or the reference is guarded by a parent, ${here:+foo$here}- "+" `isPrefixOf` mod || ":+" `isPrefixOf` mod- _ -> False-- isGuarded (T_DollarBraced _ _ v) =- rest `matches` guardRegex- where- name = concat $ oversimplify v- rest = dropWhile isVariableChar $ dropWhile (`elem` "#!") name- isGuarded _ = False- -- :? or :- with optional array index and colon- guardRegex = mkRegex "^(\\[.*\\])?:?[-?]"-- match var candidate =- if var /= candidate && map toLower var == map toLower candidate- then 1- else dist var candidate---prop_checkGlobsAsOptions1 = verify checkGlobsAsOptions "rm *.txt"-prop_checkGlobsAsOptions2 = verify checkGlobsAsOptions "ls ??.*"-prop_checkGlobsAsOptions3 = verifyNot checkGlobsAsOptions "rm -- *.txt"-prop_checkGlobsAsOptions4 = verifyNot checkGlobsAsOptions "*.txt"-prop_checkGlobsAsOptions5 = verifyNot checkGlobsAsOptions "echo 'Files:' *.txt"-prop_checkGlobsAsOptions6 = verifyNot checkGlobsAsOptions "printf '%s\\n' *"-checkGlobsAsOptions _ cmd@(T_SimpleCommand _ _ args) =- unless ((fromMaybe "" $ getCommandBasename cmd) `elem` ["echo", "printf"]) $- mapM_ check $ takeWhile (not . isEndOfArgs) (drop 1 args)- where- check v@(T_NormalWord _ (T_Glob id s:_)) | s == "*" || s == "?" =- info id 2035 "Use ./*glob* or -- *glob* so names with dashes won't become options."- check _ = return ()-- isEndOfArgs t =- case concat $ oversimplify t of- "--" -> True- ":::" -> True- "::::" -> True- _ -> False--checkGlobsAsOptions _ _ = return ()---prop_checkWhileReadPitfalls1 = verify checkWhileReadPitfalls "while read foo; do ssh $foo uptime; done < file"-prop_checkWhileReadPitfalls2 = verifyNot checkWhileReadPitfalls "while read -u 3 foo; do ssh $foo uptime; done 3< file"-prop_checkWhileReadPitfalls3 = verifyNot checkWhileReadPitfalls "while true; do ssh host uptime; done"-prop_checkWhileReadPitfalls4 = verifyNot checkWhileReadPitfalls "while read foo; do ssh $foo hostname < /dev/null; done"-prop_checkWhileReadPitfalls5 = verifyNot checkWhileReadPitfalls "while read foo; do echo ls | ssh $foo; done"-prop_checkWhileReadPitfalls6 = verifyNot checkWhileReadPitfalls "while read foo <&3; do ssh $foo; done 3< foo"-prop_checkWhileReadPitfalls7 = verify checkWhileReadPitfalls "while read foo; do if true; then ssh $foo uptime; fi; done < file"-prop_checkWhileReadPitfalls8 = verifyNot checkWhileReadPitfalls "while read foo; do ssh -n $foo uptime; done < file"-prop_checkWhileReadPitfalls9 = verify checkWhileReadPitfalls "while read foo; do ffmpeg -i foo.mkv bar.mkv -an; done"-prop_checkWhileReadPitfalls10 = verify checkWhileReadPitfalls "while read foo; do mplayer foo.ogv > file; done"-prop_checkWhileReadPitfalls11 = verifyNot checkWhileReadPitfalls "while read foo; do mplayer foo.ogv <<< q; done"-prop_checkWhileReadPitfalls12 = verifyNot checkWhileReadPitfalls "while read foo\ndo\nmplayer foo.ogv << EOF\nq\nEOF\ndone"-prop_checkWhileReadPitfalls13 = verify checkWhileReadPitfalls "while read foo; do x=$(ssh host cmd); done"-prop_checkWhileReadPitfalls14 = verify checkWhileReadPitfalls "while read foo; do echo $(ssh host cmd) < /dev/null; done"-prop_checkWhileReadPitfalls15 = verify checkWhileReadPitfalls "while read foo; do ssh $foo cmd & done"--checkWhileReadPitfalls params (T_WhileExpression id [command] contents)- | isStdinReadCommand command =- mapM_ checkMuncher contents- where- -- Map of munching commands to a function that checks if the flags should exclude it- munchers = Map.fromList [- ("ssh", (hasFlag, addFlag, "-n")),- ("ffmpeg", (hasArgument, addFlag, "-nostdin")),- ("mplayer", (hasArgument, addFlag, "-noconsolecontrols")),- ("HandBrakeCLI", (\_ _ -> False, addRedirect, "< /dev/null"))- ]- -- Use flag parsing, e.g. "-an" -> "a", "n"- hasFlag ('-':flag) = elem flag . map snd . getAllFlags- -- Simple string match, e.g. "-an" -> "-an"- hasArgument arg = elem arg . mapMaybe getLiteralString . fromJust . getCommandArgv- addFlag string cmd = fixWith [replaceEnd (getId $ getCommandTokenOrThis cmd) params 0 (' ':string)]- addRedirect string cmd = fixWith [replaceEnd (getId cmd) params 0 (' ':string)]-- isStdinReadCommand (T_Pipeline _ _ [T_Redirecting id redirs cmd]) =- let plaintext = oversimplify cmd- in headOrDefault "" plaintext == "read"- && ("-u" `notElem` plaintext)- && not (any stdinRedirect redirs)- isStdinReadCommand _ = False-- checkMuncher :: Token -> Writer [TokenComment] ()- checkMuncher (T_Pipeline _ _ (T_Redirecting _ redirs cmd:_)) = do- -- Check command substitutions regardless of the command- case cmd of- T_SimpleCommand _ vars args ->- mapM_ checkMuncher $ concat $ concatMap getCommandSequences $ concatMap getWords $ vars ++ args- _ -> return ()-- unless (any stdinRedirect redirs) $ do- -- Recurse into ifs/loops/groups/etc if this doesn't redirect- mapM_ checkMuncher $ concat $ getCommandSequences cmd-- -- Check the actual command- sequence_ $ do- name <- getCommandBasename cmd- (check, fix, flag) <- Map.lookup name munchers- guard $ not (check flag cmd)-- return $ do- info id 2095 $- name ++ " may swallow stdin, preventing this loop from working properly."- warnWithFix (getId cmd) 2095- ("Use " ++ name ++ " " ++ flag ++ " to prevent " ++ name ++ " from swallowing stdin.")- (fix flag cmd)- checkMuncher (T_Backgrounded _ t) = checkMuncher t- checkMuncher _ = return ()-- stdinRedirect (T_FdRedirect _ fd op)- | fd == "0" = True- | fd == "" =- case op of- T_IoFile _ (T_Less _) _ -> True- T_IoDuplicate _ (T_LESSAND _) _ -> True- T_HereString _ _ -> True- T_HereDoc {} -> True- _ -> False- stdinRedirect _ = False-- getWords t =- case t of- T_Assignment _ _ _ _ x -> getWordParts x- _ -> getWordParts t-checkWhileReadPitfalls _ _ = return ()---prop_checkPrefixAssign1 = verify checkPrefixAssignmentReference "var=foo echo $var"-prop_checkPrefixAssign2 = verifyNot checkPrefixAssignmentReference "var=$(echo $var) cmd"-checkPrefixAssignmentReference params t@(T_DollarBraced id _ value) =- check path- where- name = getBracedReference $ concat $ oversimplify value- path = getPath (parentMap params) t- idPath = map getId path-- check [] = return ()- check (t:rest) =- case t of- T_SimpleCommand _ vars (_:_) -> mapM_ checkVar vars- _ -> check rest- checkVar (T_Assignment aId mode aName [] value) |- aName == name && (aId `notElem` idPath) = do- warn aId 2097 "This assignment is only seen by the forked process."- warn id 2098 "This expansion will not see the mentioned assignment."- checkVar _ = return ()--checkPrefixAssignmentReference _ _ = return ()--prop_checkCharRangeGlob1 = verify checkCharRangeGlob "ls *[:digit:].jpg"-prop_checkCharRangeGlob2 = verifyNot checkCharRangeGlob "ls *[[:digit:]].jpg"-prop_checkCharRangeGlob3 = verify checkCharRangeGlob "ls [10-15]"-prop_checkCharRangeGlob4 = verifyNot checkCharRangeGlob "ls [a-zA-Z]"-prop_checkCharRangeGlob5 = verifyNot checkCharRangeGlob "tr -d [aa]" -- tr has 2060-prop_checkCharRangeGlob6 = verifyNot checkCharRangeGlob "[[ $x == [!!]* ]]"-prop_checkCharRangeGlob7 = verifyNot checkCharRangeGlob "[[ -v arr[keykey] ]]"-prop_checkCharRangeGlob8 = verifyNot checkCharRangeGlob "[[ arr[keykey] -gt 1 ]]"-prop_checkCharRangeGlob9 = verifyNot checkCharRangeGlob "read arr[keykey]" -- tr has 2313-checkCharRangeGlob p t@(T_Glob id str) |- isCharClass str && not isIgnoredCommand && not (isDereferenced t) =- if ":" `isPrefixOf` contents- && ":" `isSuffixOf` contents- && contents /= ":"- then warn id 2101 "Named class needs outer [], e.g. [[:digit:]]."- else- when ('[' `notElem` contents && hasDupes) $- info id 2102 "Ranges can only match single chars (mentioned due to duplicates)."- where- isCharClass str = "[" `isPrefixOf` str && "]" `isSuffixOf` str- contents = dropNegation . drop 1 . take (length str - 1) $ str- hasDupes = any ((>1) . length) . group . sort . filter (/= '-') $ contents- dropNegation s =- case s of- '!':rest -> rest- '^':rest -> rest- x -> x-- isIgnoredCommand = fromMaybe False $ do- cmd <- getClosestCommand (parentMap p) t- return $ isCommandMatch cmd (`elem` ["tr", "read"])-- -- Check if this is a dereferencing context like [[ -v array[operandhere] ]]- isDereferenced = fromMaybe False . msum . map isDereferencingOp . getPath (parentMap p)- isDereferencingOp t =- case t of- TC_Binary _ DoubleBracket str _ _ -> return $ isDereferencingBinaryOp str- TC_Unary _ _ str _ -> return $ str == "-v"- T_SimpleCommand {} -> return False- _ -> Nothing-checkCharRangeGlob _ _ = return ()----prop_checkCdAndBack1 = verify checkCdAndBack "for f in *; do cd $f; git pull; cd ..; done"-prop_checkCdAndBack2 = verifyNot checkCdAndBack "for f in *; do cd $f || continue; git pull; cd ..; done"-prop_checkCdAndBack3 = verifyNot checkCdAndBack "while [[ $PWD != / ]]; do cd ..; done"-prop_checkCdAndBack4 = verify checkCdAndBack "cd $tmp; foo; cd -"-prop_checkCdAndBack5 = verifyNot checkCdAndBack "cd ..; foo; cd .."-prop_checkCdAndBack6 = verify checkCdAndBack "for dir in */; do cd \"$dir\"; some_cmd; cd ..; done"-prop_checkCdAndBack7 = verifyNot checkCdAndBack "set -e; for dir in */; do cd \"$dir\"; some_cmd; cd ..; done"-prop_checkCdAndBack8 = verifyNot checkCdAndBack "cd tmp\nfoo\n# shellcheck disable=SC2103\ncd ..\n"-checkCdAndBack params t =- unless (hasSetE params) $ mapM_ doList $ getCommandSequences t- where- isCdRevert t =- case oversimplify t of- [_, p] -> p `elem` ["..", "-"]- _ -> False-- getCandidate (T_Annotation _ _ x) = getCandidate x- getCandidate (T_Pipeline id _ [x]) | x `isCommand` "cd" = return x- getCandidate _ = Nothing-- findCdPair list =- case list of- (a:b:rest) ->- if isCdRevert b && not (isCdRevert a)- then return $ getId b- else findCdPair (b:rest)- _ -> Nothing-- doList list = sequence_ $ do- cd <- findCdPair $ mapMaybe getCandidate list- return $ info cd 2103 "Use a ( subshell ) to avoid having to cd back."--prop_checkLoopKeywordScope1 = verify checkLoopKeywordScope "continue 2"-prop_checkLoopKeywordScope2 = verify checkLoopKeywordScope "for f; do ( break; ); done"-prop_checkLoopKeywordScope3 = verify checkLoopKeywordScope "if true; then continue; fi"-prop_checkLoopKeywordScope4 = verifyNot checkLoopKeywordScope "while true; do break; done"-prop_checkLoopKeywordScope5 = verify checkLoopKeywordScope "if true; then break; fi"-prop_checkLoopKeywordScope6 = verify checkLoopKeywordScope "while true; do true | { break; }; done"-prop_checkLoopKeywordScope7 = verifyNot checkLoopKeywordScope "#!/bin/ksh\nwhile true; do true | { break; }; done"-checkLoopKeywordScope params t |- name `elem` map Just ["continue", "break"] =- if not $ any isLoop path- then if any isFunction $ take 1 path- -- breaking at a source/function invocation is an abomination. Let's ignore it.- then err (getId t) 2104 $ "In functions, use return instead of " ++ fromJust name ++ "."- else err (getId t) 2105 $ fromJust name ++ " is only valid in loops."- else case map subshellType $ filter (not . isFunction) path of- Just str:_ -> warn (getId t) 2106 $- "This only exits the subshell caused by the " ++ str ++ "."- _ -> return ()- where- name = getCommandName t- path = let p = getPath (parentMap params) t in filter relevant p- subshellType t = case leadType params t of- NoneScope -> Nothing- SubshellScope str -> return str- relevant t = isLoop t || isFunction t || isJust (subshellType t)-checkLoopKeywordScope _ _ = return ()---prop_checkFunctionDeclarations1 = verify checkFunctionDeclarations "#!/bin/ksh\nfunction foo() { command foo --lol \"$@\"; }"-prop_checkFunctionDeclarations2 = verify checkFunctionDeclarations "#!/bin/dash\nfunction foo { lol; }"-prop_checkFunctionDeclarations3 = verifyNot checkFunctionDeclarations "foo() { echo bar; }"-checkFunctionDeclarations params- (T_Function id (FunctionKeyword hasKeyword) (FunctionParentheses hasParens) _ _) =- case shellType params of- Bash -> return ()- Ksh ->- when (hasKeyword && hasParens) $- err id 2111 "ksh does not allow 'function' keyword and '()' at the same time."- Dash -> forSh- Sh -> forSh-- where- forSh = do- when (hasKeyword && hasParens) $- warn id 2112 "'function' keyword is non-standard. Delete it."- when (hasKeyword && not hasParens) $- warn id 2113 "'function' keyword is non-standard. Use 'foo()' instead of 'function foo'."-checkFunctionDeclarations _ _ = return ()----prop_checkStderrPipe1 = verify checkStderrPipe "#!/bin/ksh\nfoo |& bar"-prop_checkStderrPipe2 = verifyNot checkStderrPipe "#!/bin/bash\nfoo |& bar"-checkStderrPipe params =- case shellType params of- Ksh -> match- _ -> const $ return ()- where- match (T_Pipe id "|&") =- err id 2118 "Ksh does not support |&. Use 2>&1 |."- match _ = return ()--prop_checkUnpassedInFunctions1 = verifyTree checkUnpassedInFunctions "foo() { echo $1; }; foo"-prop_checkUnpassedInFunctions2 = verifyNotTree checkUnpassedInFunctions "foo() { echo $1; };"-prop_checkUnpassedInFunctions3 = verifyNotTree checkUnpassedInFunctions "foo() { echo $lol; }; foo"-prop_checkUnpassedInFunctions4 = verifyNotTree checkUnpassedInFunctions "foo() { echo $0; }; foo"-prop_checkUnpassedInFunctions5 = verifyNotTree checkUnpassedInFunctions "foo() { echo $1; }; foo 'lol'; foo"-prop_checkUnpassedInFunctions6 = verifyNotTree checkUnpassedInFunctions "foo() { set -- *; echo $1; }; foo"-prop_checkUnpassedInFunctions7 = verifyTree checkUnpassedInFunctions "foo() { echo $1; }; foo; foo;"-prop_checkUnpassedInFunctions8 = verifyNotTree checkUnpassedInFunctions "foo() { echo $((1)); }; foo;"-prop_checkUnpassedInFunctions9 = verifyNotTree checkUnpassedInFunctions "foo() { echo $(($b)); }; foo;"-prop_checkUnpassedInFunctions10 = verifyNotTree checkUnpassedInFunctions "foo() { echo $!; }; foo;"-prop_checkUnpassedInFunctions11 = verifyNotTree checkUnpassedInFunctions "foo() { bar() { echo $1; }; bar baz; }; foo;"-prop_checkUnpassedInFunctions12 = verifyNotTree checkUnpassedInFunctions "foo() { echo ${!var*}; }; foo;"-prop_checkUnpassedInFunctions13 = verifyNotTree checkUnpassedInFunctions "# shellcheck disable=SC2120\nfoo() { echo $1; }\nfoo\n"-prop_checkUnpassedInFunctions14 = verifyTree checkUnpassedInFunctions "foo() { echo $#; }; foo"-checkUnpassedInFunctions params root =- execWriter $ mapM_ warnForGroup referenceGroups- where- functionMap :: Map.Map String Token- functionMap = Map.fromList $- map (\t@(T_Function _ _ _ name _) -> (name,t)) functions- functions = execWriter $ doAnalysis (tell . maybeToList . findFunction) root-- findFunction t@(T_Function id _ _ name body)- | any (isPositionalReference t) flow && not (any isPositionalAssignment flow)- = return t- where flow = getVariableFlow params body- findFunction _ = Nothing-- isPositionalAssignment x =- case x of- Assignment (_, _, str, _) -> isPositional str- _ -> False- isPositionalReference function x =- case x of- Reference (_, t, str) -> isPositional str && t `isDirectChildOf` function- _ -> False-- isDirectChildOf child parent = fromMaybe False $ do- function <- find (\x -> case x of- T_Function {} -> True- T_Script {} -> True -- for sourced files- _ -> False) $- getPath (parentMap params) child- return $ getId parent == getId function-- referenceList :: [(String, Bool, Token)]- referenceList = execWriter $- doAnalysis (sequence_ . checkCommand) root- checkCommand :: Token -> Maybe (Writer [(String, Bool, Token)] ())- checkCommand t@(T_SimpleCommand _ _ (cmd:args)) = do- str <- getLiteralString cmd- guard $ Map.member str functionMap- return $ tell [(str, null args, t)]- checkCommand _ = Nothing-- isPositional str = str == "*" || str == "@" || str == "#"- || (all isDigit str && str /= "0" && str /= "")-- isArgumentless (_, b, _) = b- referenceGroups = Map.elems $ foldr updateWith Map.empty referenceList- updateWith x@(name, _, _) = Map.insertWith (++) name [x]-- warnForGroup group =- -- Allow ignoring SC2120 on the function to ignore all calls- when (all isArgumentless group && not ignoring) $ do- mapM_ suggestParams group- warnForDeclaration func name- where (name, func) = getFunction group- ignoring = shouldIgnoreCode params 2120 func-- suggestParams (name, _, thing) =- info (getId thing) 2119 $- "Use " ++ (e4m name) ++ " \"$@\" if function's $1 should mean script's $1."- warnForDeclaration func name =- warn (getId func) 2120 $- name ++ " references arguments, but none are ever passed."-- getFunction ((name, _, _):_) =- (name, functionMap Map.! name)---prop_checkOverridingPath1 = verify checkOverridingPath "PATH=\"$var/$foo\""-prop_checkOverridingPath2 = verify checkOverridingPath "PATH=\"mydir\""-prop_checkOverridingPath3 = verify checkOverridingPath "PATH=/cow/foo"-prop_checkOverridingPath4 = verifyNot checkOverridingPath "PATH=/cow/foo/bin"-prop_checkOverridingPath5 = verifyNot checkOverridingPath "PATH='/bin:/sbin'"-prop_checkOverridingPath6 = verifyNot checkOverridingPath "PATH=\"$var/$foo\" cmd"-prop_checkOverridingPath7 = verifyNot checkOverridingPath "PATH=$OLDPATH"-prop_checkOverridingPath8 = verifyNot checkOverridingPath "PATH=$PATH:/stuff"-checkOverridingPath _ (T_SimpleCommand _ vars []) =- mapM_ checkVar vars- where- checkVar (T_Assignment id Assign "PATH" [] word)- | not $ any (`isInfixOf` string) ["/bin", "/sbin" ] = do- when ('/' `elem` string && ':' `notElem` string) $ notify id- when (isLiteral word && ':' `notElem` string && '/' `notElem` string) $ notify id- where string = concat $ oversimplify word- checkVar _ = return ()- notify id = warn id 2123 "PATH is the shell search path. Use another name."-checkOverridingPath _ _ = return ()--prop_checkTildeInPath1 = verify checkTildeInPath "PATH=\"$PATH:~/bin\""-prop_checkTildeInPath2 = verify checkTildeInPath "PATH='~foo/bin'"-prop_checkTildeInPath3 = verifyNot checkTildeInPath "PATH=~/bin"-checkTildeInPath _ (T_SimpleCommand _ vars _) =- mapM_ checkVar vars- where- checkVar (T_Assignment id Assign "PATH" [] (T_NormalWord _ parts))- | any (\x -> isQuoted x && hasTilde x) parts =- warn id 2147 "Literal tilde in PATH works poorly across programs."- checkVar _ = return ()-- hasTilde t = '~' `elem` onlyLiteralString t- isQuoted T_DoubleQuoted {} = True- isQuoted T_SingleQuoted {} = True- isQuoted _ = False-checkTildeInPath _ _ = return ()--prop_checkUnsupported3 = verify checkUnsupported "#!/bin/sh\ncase foo in bar) baz ;& esac"-prop_checkUnsupported4 = verify checkUnsupported "#!/bin/ksh\ncase foo in bar) baz ;;& esac"-prop_checkUnsupported5 = verify checkUnsupported "#!/bin/bash\necho \"${ ls; }\""-checkUnsupported params t =- unless (null support || (shellType params `elem` support)) $- report name- where- (name, support) = shellSupport t- report s = err (getId t) 2127 $- "To use " ++ s ++ ", specify #!/usr/bin/env " ++- (intercalate " or " . map (map toLower . show) $ support)---- TODO: Move more of these checks here-shellSupport t =- case t of- T_CaseExpression _ _ list -> forCase (map (\(a,_,_) -> a) list)- T_DollarBraceCommandExpansion {} -> ("${ ..; } command expansion", [Ksh])- _ -> ("", [])- where- forCase seps | CaseContinue `elem` seps = ("cases with ;;&", [Bash])- forCase seps | CaseFallThrough `elem` seps = ("cases with ;&", [Bash, Ksh])- forCase _ = ("", [])---groupWith f = groupBy ((==) `on` f)--prop_checkMultipleAppends1 = verify checkMultipleAppends "foo >> file; bar >> file; baz >> file;"-prop_checkMultipleAppends2 = verify checkMultipleAppends "foo >> file; bar | grep f >> file; baz >> file;"-prop_checkMultipleAppends3 = verifyNot checkMultipleAppends "foo < file; bar < file; baz < file;"-checkMultipleAppends params t =- mapM_ checkList $ getCommandSequences t- where- checkList list =- mapM_ checkGroup (groupWith (fmap fst) $ map getTarget list)- checkGroup (Just (_,id):_:_:_) =- style id 2129- "Consider using { cmd1; cmd2; } >> file instead of individual redirects."- checkGroup _ = return ()- getTarget (T_Annotation _ _ t) = getTarget t- getTarget (T_Pipeline _ _ args@(_:_)) = getTarget (last args)- getTarget (T_Redirecting id list _) = do- file <- mapMaybe getAppend list !!! 0- return (file, id)- getTarget _ = Nothing- getAppend (T_FdRedirect _ _ (T_IoFile _ T_DGREAT {} f)) = return f- getAppend _ = Nothing---prop_checkSuspiciousIFS1 = verify checkSuspiciousIFS "IFS=\"\\n\""-prop_checkSuspiciousIFS2 = verifyNot checkSuspiciousIFS "IFS=$'\\t'"-prop_checkSuspiciousIFS3 = verify checkSuspiciousIFS "IFS=' \\t\\n'"-checkSuspiciousIFS params (T_Assignment _ _ "IFS" [] value) =- mapM_ check $ getLiteralString value- where- hasDollarSingle = shellType params == Bash || shellType params == Ksh- n = if hasDollarSingle then "$'\\n'" else "'<literal linefeed here>'"- t = if hasDollarSingle then "$'\\t'" else "\"$(printf '\\t')\""- check value =- case value of- "\\n" -> suggest n- "\\t" -> suggest t- x | '\\' `elem` x -> suggest2 "a literal backslash"- x | 'n' `elem` x -> suggest2 "the literal letter 'n'"- x | 't' `elem` x -> suggest2 "the literal letter 't'"- _ -> return ()- suggest r = warn (getId value) 2141 $ "This backslash is literal. Did you mean IFS=" ++ r ++ " ?"- suggest2 desc = warn (getId value) 2141 $ "This IFS value contains " ++ desc ++ ". For tabs/linefeeds/escapes, use $'..', literal, or printf."-checkSuspiciousIFS _ _ = return ()---prop_checkGrepQ1 = verify checkShouldUseGrepQ "[[ $(foo | grep bar) ]]"-prop_checkGrepQ2 = verify checkShouldUseGrepQ "[ -z $(fgrep lol) ]"-prop_checkGrepQ3 = verify checkShouldUseGrepQ "[ -n \"$(foo | zgrep lol)\" ]"-prop_checkGrepQ4 = verifyNot checkShouldUseGrepQ "[ -z $(grep bar | cmd) ]"-prop_checkGrepQ5 = verifyNot checkShouldUseGrepQ "rm $(ls | grep file)"-prop_checkGrepQ6 = verifyNot checkShouldUseGrepQ "[[ -n $(pgrep foo) ]]"-checkShouldUseGrepQ params t =- sequence_ $ case t of- TC_Nullary id _ token -> check id True token- TC_Unary id _ "-n" token -> check id True token- TC_Unary id _ "-z" token -> check id False token- _ -> fail "not check"- where- check id bool token = do- name <- getFinalGrep token- let op = if bool then "-n" else "-z"- let flip = if bool then "" else "! "- return . style id 2143 $- "Use " ++ flip ++ name ++ " -q instead of " ++- "comparing output with [ " ++ op ++ " .. ]."-- getFinalGrep t = do- cmds <- getPipeline t- guard . not . null $ cmds- name <- getCommandBasename $ last cmds- guard . isGrep $ name- return name- getPipeline t =- case t of- T_NormalWord _ [x] -> getPipeline x- T_DoubleQuoted _ [x] -> getPipeline x- T_DollarExpansion _ [x] -> getPipeline x- T_Pipeline _ _ cmds -> return cmds- _ -> fail "unknown"- isGrep = (`elem` ["grep", "egrep", "fgrep", "zgrep"])--prop_checkTestArgumentSplitting1 = verify checkTestArgumentSplitting "[ -e *.mp3 ]"-prop_checkTestArgumentSplitting2 = verifyNot checkTestArgumentSplitting "[[ $a == *b* ]]"-prop_checkTestArgumentSplitting3 = verify checkTestArgumentSplitting "[[ *.png == '' ]]"-prop_checkTestArgumentSplitting4 = verify checkTestArgumentSplitting "[[ foo == f{o,oo,ooo} ]]"-prop_checkTestArgumentSplitting5 = verify checkTestArgumentSplitting "[[ $@ ]]"-prop_checkTestArgumentSplitting6 = verify checkTestArgumentSplitting "[ -e $@ ]"-prop_checkTestArgumentSplitting7 = verify checkTestArgumentSplitting "[ $@ == $@ ]"-prop_checkTestArgumentSplitting8 = verify checkTestArgumentSplitting "[[ $@ = $@ ]]"-prop_checkTestArgumentSplitting9 = verifyNot checkTestArgumentSplitting "[[ foo =~ bar{1,2} ]]"-prop_checkTestArgumentSplitting10 = verifyNot checkTestArgumentSplitting "[ \"$@\" ]"-prop_checkTestArgumentSplitting11 = verify checkTestArgumentSplitting "[[ \"$@\" ]]"-prop_checkTestArgumentSplitting12 = verify checkTestArgumentSplitting "[ *.png ]"-prop_checkTestArgumentSplitting13 = verify checkTestArgumentSplitting "[ \"$@\" == \"\" ]"-prop_checkTestArgumentSplitting14 = verify checkTestArgumentSplitting "[[ \"$@\" == \"\" ]]"-prop_checkTestArgumentSplitting15 = verifyNot checkTestArgumentSplitting "[[ \"$*\" == \"\" ]]"-prop_checkTestArgumentSplitting16 = verifyNot checkTestArgumentSplitting "[[ -v foo[123] ]]"-prop_checkTestArgumentSplitting17 = verifyNot checkTestArgumentSplitting "#!/bin/ksh\n[ -e foo* ]"-prop_checkTestArgumentSplitting18 = verify checkTestArgumentSplitting "#!/bin/ksh\n[ -d foo* ]"-prop_checkTestArgumentSplitting19 = verifyNot checkTestArgumentSplitting "[[ var[x] -eq 2*3 ]]"-prop_checkTestArgumentSplitting20 = verify checkTestArgumentSplitting "[ var[x] -eq 2 ]"-prop_checkTestArgumentSplitting21 = verify checkTestArgumentSplitting "[ 6 -eq 2*3 ]"-checkTestArgumentSplitting :: Parameters -> Token -> Writer [TokenComment] ()-checkTestArgumentSplitting params t =- case t of- (TC_Unary _ typ op token) | isGlob token ->- if op == "-v"- then- when (typ == SingleBracket) $- err (getId token) 2208 $- "Use [[ ]] or quote arguments to -v to avoid glob expansion."- else- if (typ == SingleBracket && shellType params == Ksh)- then- -- Ksh appears to stop processing after unrecognized tokens, so operators- -- will effectively work with globs, but only the first match.- when (op `elem` [['-', c] | c <- "bcdfgkprsuwxLhNOGRS" ]) $- warn (getId token) 2245 $- op ++ " only applies to the first expansion of this glob. Use a loop to check any/all."- else- err (getId token) 2144 $- op ++ " doesn't work with globs. Use a for loop."-- (TC_Nullary _ typ token) -> do- checkBraces typ token- checkGlobs typ token- when (typ == DoubleBracket) $- checkArrays typ token-- (TC_Unary _ typ op token) -> checkAll typ token-- (TC_Binary _ typ op lhs rhs) | op `elem` arithmeticBinaryTestOps ->- if typ == DoubleBracket- then- mapM_ (\c -> do- checkArrays typ c- checkBraces typ c) [lhs, rhs]- else- mapM_ (\c -> do- checkNumericalGlob typ c- checkArrays typ c- checkBraces typ c) [lhs, rhs]-- (TC_Binary _ typ op lhs rhs) ->- if op `elem` ["=", "==", "!=", "=~"]- then do- checkAll typ lhs- checkArrays typ rhs- checkBraces typ rhs- else mapM_ (checkAll typ) [lhs, rhs]- _ -> return ()- where- checkAll typ token = do- checkArrays typ token- checkBraces typ token- checkGlobs typ token-- checkArrays typ token =- when (any isArrayExpansion $ getWordParts token) $- if typ == SingleBracket- then warn (getId token) 2198 "Arrays don't work as operands in [ ]. Use a loop (or concatenate with * instead of @)."- else err (getId token) 2199 "Arrays implicitly concatenate in [[ ]]. Use a loop (or explicit * instead of @)."-- checkBraces typ token =- when (any isBraceExpansion $ getWordParts token) $- if typ == SingleBracket- then warn (getId token) 2200 "Brace expansions don't work as operands in [ ]. Use a loop."- else err (getId token) 2201 "Brace expansion doesn't happen in [[ ]]. Use a loop."-- checkGlobs typ token =- when (isGlob token) $- if typ == SingleBracket- then warn (getId token) 2202 "Globs don't work as operands in [ ]. Use a loop."- else err (getId token) 2203 "Globs are ignored in [[ ]] except right of =/!=. Use a loop."-- checkNumericalGlob SingleBracket token =- -- var[x] and x*2 look like globs- when (shellType params /= Ksh && isGlob token) $- err (getId token) 2255 "[ ] does not apply arithmetic evaluation. Evaluate with $((..)) for numbers, or use string comparator for strings."---prop_checkReadWithoutR1 = verify checkReadWithoutR "read -a foo"-prop_checkReadWithoutR2 = verifyNot checkReadWithoutR "read -ar foo"-prop_checkReadWithoutR3 = verifyNot checkReadWithoutR "read -t 0"-prop_checkReadWithoutR4 = verifyNot checkReadWithoutR "read -t 0 && read --d '' -r bar"-prop_checkReadWithoutR5 = verifyNot checkReadWithoutR "read -t 0 foo < file.txt"-prop_checkReadWithoutR6 = verifyNot checkReadWithoutR "read -u 3 -t 0"-checkReadWithoutR _ t@T_SimpleCommand {} | t `isUnqualifiedCommand` "read"- && "r" `notElem` map snd flags && not has_t0 =- info (getId $ getCommandTokenOrThis t) 2162 "read without -r will mangle backslashes."- where- flags = getAllFlags t- has_t0 = Just "0" == do- parsed <- getGnuOpts flagsForRead $ arguments t- (_, t) <- lookup "t" parsed- getLiteralString t--checkReadWithoutR _ _ = return ()--prop_checkUncheckedCd1 = verifyTree checkUncheckedCdPushdPopd "cd ~/src; rm -r foo"-prop_checkUncheckedCd2 = verifyNotTree checkUncheckedCdPushdPopd "cd ~/src || exit; rm -r foo"-prop_checkUncheckedCd3 = verifyNotTree checkUncheckedCdPushdPopd "set -e; cd ~/src; rm -r foo"-prop_checkUncheckedCd4 = verifyNotTree checkUncheckedCdPushdPopd "if cd foo; then rm foo; fi"-prop_checkUncheckedCd5 = verifyTree checkUncheckedCdPushdPopd "if true; then cd foo; fi"-prop_checkUncheckedCd6 = verifyNotTree checkUncheckedCdPushdPopd "cd .."-prop_checkUncheckedCd7 = verifyNotTree checkUncheckedCdPushdPopd "#!/bin/bash -e\ncd foo\nrm bar"-prop_checkUncheckedCd8 = verifyNotTree checkUncheckedCdPushdPopd "set -o errexit; cd foo; rm bar"-prop_checkUncheckedCd9 = verifyTree checkUncheckedCdPushdPopd "builtin cd ~/src; rm -r foo"-prop_checkUncheckedPushd1 = verifyTree checkUncheckedCdPushdPopd "pushd ~/src; rm -r foo"-prop_checkUncheckedPushd2 = verifyNotTree checkUncheckedCdPushdPopd "pushd ~/src || exit; rm -r foo"-prop_checkUncheckedPushd3 = verifyNotTree checkUncheckedCdPushdPopd "set -e; pushd ~/src; rm -r foo"-prop_checkUncheckedPushd4 = verifyNotTree checkUncheckedCdPushdPopd "if pushd foo; then rm foo; fi"-prop_checkUncheckedPushd5 = verifyTree checkUncheckedCdPushdPopd "if true; then pushd foo; fi"-prop_checkUncheckedPushd6 = verifyNotTree checkUncheckedCdPushdPopd "pushd .."-prop_checkUncheckedPushd7 = verifyNotTree checkUncheckedCdPushdPopd "#!/bin/bash -e\npushd foo\nrm bar"-prop_checkUncheckedPushd8 = verifyNotTree checkUncheckedCdPushdPopd "set -o errexit; pushd foo; rm bar"-prop_checkUncheckedPushd9 = verifyNotTree checkUncheckedCdPushdPopd "pushd -n foo"-prop_checkUncheckedPopd1 = verifyTree checkUncheckedCdPushdPopd "popd; rm -r foo"-prop_checkUncheckedPopd2 = verifyNotTree checkUncheckedCdPushdPopd "popd || exit; rm -r foo"-prop_checkUncheckedPopd3 = verifyNotTree checkUncheckedCdPushdPopd "set -e; popd; rm -r foo"-prop_checkUncheckedPopd4 = verifyNotTree checkUncheckedCdPushdPopd "if popd; then rm foo; fi"-prop_checkUncheckedPopd5 = verifyTree checkUncheckedCdPushdPopd "if true; then popd; fi"-prop_checkUncheckedPopd6 = verifyTree checkUncheckedCdPushdPopd "popd"-prop_checkUncheckedPopd7 = verifyNotTree checkUncheckedCdPushdPopd "#!/bin/bash -e\npopd\nrm bar"-prop_checkUncheckedPopd8 = verifyNotTree checkUncheckedCdPushdPopd "set -o errexit; popd; rm bar"-prop_checkUncheckedPopd9 = verifyNotTree checkUncheckedCdPushdPopd "popd -n foo"-prop_checkUncheckedPopd10 = verifyNotTree checkUncheckedCdPushdPopd "cd ../.."-prop_checkUncheckedPopd11 = verifyNotTree checkUncheckedCdPushdPopd "cd ../.././.."-prop_checkUncheckedPopd12 = verifyNotTree checkUncheckedCdPushdPopd "cd /"-prop_checkUncheckedPopd13 = verifyTree checkUncheckedCdPushdPopd "cd ../../.../.."--checkUncheckedCdPushdPopd params root =- if hasSetE params then- []- else execWriter $ doAnalysis checkElement root- where- checkElement t@T_SimpleCommand {}- | name `elem` ["cd", "pushd", "popd"]- && not (isSafeDir t)- && not (name `elem` ["pushd", "popd"] && ("n" `elem` map snd (getAllFlags t)))- && not (isCondition $ getPath (parentMap params) t) =- warnWithFix (getId t) 2164- ("Use '" ++ name ++ " ... || exit' or '" ++ name ++ " ... || return' in case " ++ name ++ " fails.")- (fixWith [replaceEnd (getId t) params 0 " || exit"])- where name = getName t- checkElement _ = return ()- getName t = fromMaybe "" $ getCommandName t- isSafeDir t = case oversimplify t of- [_, str] -> str `matches` regex- _ -> False- regex = mkRegex "^/*((\\.|\\.\\.)/+)*(\\.|\\.\\.)?$"--prop_checkLoopVariableReassignment1 = verify checkLoopVariableReassignment "for i in *; do for i in *.bar; do true; done; done"-prop_checkLoopVariableReassignment2 = verify checkLoopVariableReassignment "for i in *; do for((i=0; i<3; i++)); do true; done; done"-prop_checkLoopVariableReassignment3 = verifyNot checkLoopVariableReassignment "for i in *; do for j in *.bar; do true; done; done"-prop_checkLoopVariableReassignment4 = verifyNot checkLoopVariableReassignment "for _ in *; do for _ in *.bar; do true; done; done"-checkLoopVariableReassignment params token =- sequence_ $ case token of- T_ForIn {} -> check- T_ForArithmetic {} -> check- _ -> Nothing- where- check = do- str <- loopVariable token- guard $ str /= "_"- next <- find (\x -> loopVariable x == Just str) path- return $ do- warn (getId token) 2165 "This nested loop overrides the index variable of its parent."- warn (getId next) 2167 "This parent loop has its index variable overridden."- path = drop 1 $ getPath (parentMap params) token- loopVariable :: Token -> Maybe String- loopVariable t =- case t of- T_ForIn _ s _ _ -> return s- T_ForArithmetic _- (TA_Sequence _- [TA_Assignment _ "="- (TA_Variable _ var _ ) _])- _ _ _ -> return var- _ -> fail "not loop"--prop_checkTrailingBracket1 = verify checkTrailingBracket "if -z n ]]; then true; fi "-prop_checkTrailingBracket2 = verifyNot checkTrailingBracket "if [[ -z n ]]; then true; fi "-prop_checkTrailingBracket3 = verify checkTrailingBracket "a || b ] && thing"-prop_checkTrailingBracket4 = verifyNot checkTrailingBracket "run [ foo ]"-prop_checkTrailingBracket5 = verifyNot checkTrailingBracket "run bar ']'"-checkTrailingBracket _ token =- case token of- T_SimpleCommand _ _ tokens@(_:_) -> check (last tokens) token- _ -> return ()- where- check (T_NormalWord id [T_Literal _ str]) command- | str `elem` [ "]]", "]" ]- && opposite `notElem` parameters- = warn id 2171 $- "Found trailing " ++ str ++ " outside test. Add missing " ++ opposite ++ " or quote if intentional."- where- opposite = invert str- parameters = oversimplify command- check _ _ = return ()- invert s =- case s of- "]]" -> "[["- "]" -> "["- x -> x--prop_checkReturnAgainstZero1 = verify checkReturnAgainstZero "[ $? -eq 0 ]"-prop_checkReturnAgainstZero2 = verify checkReturnAgainstZero "[[ \"$?\" -gt 0 ]]"-prop_checkReturnAgainstZero3 = verify checkReturnAgainstZero "[[ 0 -ne $? ]]"-prop_checkReturnAgainstZero4 = verifyNot checkReturnAgainstZero "[[ $? -eq 4 ]]"-prop_checkReturnAgainstZero5 = verify checkReturnAgainstZero "[[ 0 -eq $? ]]"-prop_checkReturnAgainstZero6 = verifyNot checkReturnAgainstZero "[[ $R -eq 0 ]]"-prop_checkReturnAgainstZero7 = verify checkReturnAgainstZero "(( $? == 0 ))"-prop_checkReturnAgainstZero8 = verify checkReturnAgainstZero "(( $? ))"-prop_checkReturnAgainstZero9 = verify checkReturnAgainstZero "(( ! $? ))"-prop_checkReturnAgainstZero10 = verifyNot checkReturnAgainstZero "x=$(( $? > 0 ))"-prop_checkReturnAgainstZero11 = verify checkReturnAgainstZero "(( ! ! ! $? ))"-prop_checkReturnAgainstZero12 = verify checkReturnAgainstZero "[ ! $? -eq 0 ]"-prop_checkReturnAgainstZero13 = verifyNot checkReturnAgainstZero "(( ! $? && $? > 42))"-prop_checkReturnAgainstZero14 = verifyNot checkReturnAgainstZero "[[ -e foo || $? -eq 0 ]]"-prop_checkReturnAgainstZero15 = verifyNot checkReturnAgainstZero "(( $?, n=1 ))"-prop_checkReturnAgainstZero16 = verifyNot checkReturnAgainstZero "(( $? || $? == 4 ))"-prop_checkReturnAgainstZero17 = verifyNot checkReturnAgainstZero "(( $? + 0 ))"-prop_checkReturnAgainstZero18 = verifyNot checkReturnAgainstZero "f() { if [ $? -eq 0 ]; then :; fi; }"-prop_checkReturnAgainstZero19 = verifyNot checkReturnAgainstZero "f() ( [ $? -eq 0 ] || exit 42; )"-prop_checkReturnAgainstZero20 = verify checkReturnAgainstZero "f() { if :; then x; [ $? -eq 0 ] && exit; fi; }"-prop_checkReturnAgainstZero21 = verify checkReturnAgainstZero "(( ( $? ) ))"-prop_checkReturnAgainstZero22 = verify checkReturnAgainstZero "[[ ( $? -eq 0 ) ]]"-checkReturnAgainstZero params token =- case token of- TC_Binary id _ op lhs rhs -> check op lhs rhs- TA_Binary id op lhs rhs- | op `elem` [">", "<", ">=", "<=", "==", "!="] -> check op lhs rhs- TA_Unary id op@"!" exp- | isExitCode exp -> message (checksSuccessLhs op) (getId exp)- TA_Sequence _ [exp]- | isExitCode exp -> message False (getId exp)- _ -> return ()- where- -- We don't want to warn about composite expressions like- -- [[ $? -eq 0 || $? -eq 4 ]] since these can be annoying to rewrite.- isOnlyTestInCommand t =- case getPath (parentMap params) t of- _:(T_Condition {}):_ -> True- _:(T_Arithmetic {}):_ -> True- _:(TA_Sequence _ [_]):(T_Arithmetic {}):_ -> True-- -- Some negations and groupings are also fine- _:next@(TC_Unary _ _ "!" _):_ -> isOnlyTestInCommand next- _:next@(TA_Unary _ "!" _):_ -> isOnlyTestInCommand next- _:next@(TC_Group {}):_ -> isOnlyTestInCommand next- _:next@(TA_Sequence _ [_]):_ -> isOnlyTestInCommand next- _:next@(TA_Parentesis _ _):_ -> isOnlyTestInCommand next- _ -> False-- -- TODO: Do better $? tracking and filter on whether- -- the target command is in the same function- getFirstCommandInFunction = f- where- f t = case t of- T_Function _ _ _ _ x -> f x- T_BraceGroup _ (x:_) -> f x- T_Subshell _ (x:_) -> f x- T_Annotation _ _ x -> f x- T_AndIf _ x _ -> f x- T_OrIf _ x _ -> f x- T_Pipeline _ _ (x:_) -> f x- T_Redirecting _ _ (T_IfExpression _ (((x:_),_):_) _) -> f x- x -> x-- isFirstCommandInFunction = fromMaybe False $ do- let path = getPath (parentMap params) token- func <- listToMaybe $ filter isFunction path- cmd <- getClosestCommand (parentMap params) token- return $ getId cmd == getId (getFirstCommandInFunction func)-- -- Is "$? op 0" trying to check if the command succeeded?- checksSuccessLhs op = not $ op `elem` ["-gt", "-ne", "!=", "!"]- -- Is "0 op $?" trying to check if the command succeeded?- checksSuccessRhs op = op `notElem` ["-ne", "!="]-- check op lhs rhs =- if isZero rhs && isExitCode lhs- then message (checksSuccessLhs op) (getId lhs)- else when (isZero lhs && isExitCode rhs) $ message (checksSuccessRhs op) (getId rhs)- isZero t = getLiteralString t == Just "0"- isExitCode t =- case getWordParts t of- [T_DollarBraced _ _ l] -> concat (oversimplify l) == "?"- _ -> False-- message forSuccess id = when (isOnlyTestInCommand token && not isFirstCommandInFunction) $ style id 2181 $- "Check exit code directly with e.g. 'if " ++ (if forSuccess then "" else "! ") ++ "mycmd;', not indirectly with $?."---prop_checkRedirectedNowhere1 = verify checkRedirectedNowhere "> file"-prop_checkRedirectedNowhere2 = verify checkRedirectedNowhere "> file | grep foo"-prop_checkRedirectedNowhere3 = verify checkRedirectedNowhere "grep foo | > bar"-prop_checkRedirectedNowhere4 = verifyNot checkRedirectedNowhere "grep foo > bar"-prop_checkRedirectedNowhere5 = verifyNot checkRedirectedNowhere "foo | grep bar > baz"-prop_checkRedirectedNowhere6 = verifyNot checkRedirectedNowhere "var=$(value) 2> /dev/null"-prop_checkRedirectedNowhere7 = verifyNot checkRedirectedNowhere "var=$(< file)"-prop_checkRedirectedNowhere8 = verifyNot checkRedirectedNowhere "var=`< file`"-checkRedirectedNowhere params token =- case token of- T_Pipeline _ _ [single] -> sequence_ $ do- redir <- getDanglingRedirect single- guard . not $ isInExpansion token- return $ warn (getId redir) 2188 "This redirection doesn't have a command. Move to its command (or use 'true' as no-op)."-- T_Pipeline _ _ list -> forM_ list $ \x -> sequence_ $ do- redir <- getDanglingRedirect x- return $ err (getId redir) 2189 "You can't have | between this redirection and the command it should apply to."-- _ -> return ()- where- isInExpansion t =- case drop 1 $ getPath (parentMap params) t of- T_DollarExpansion _ [_] : _ -> True- T_Backticked _ [_] : _ -> True- t@T_Annotation {} : _ -> isInExpansion t- _ -> False- getDanglingRedirect token =- case token of- T_Redirecting _ (first:_) (T_SimpleCommand _ [] []) -> return first- _ -> Nothing---prop_checkArrayAssignmentIndices1 = verifyTree checkArrayAssignmentIndices "declare -A foo; foo=(bar)"-prop_checkArrayAssignmentIndices2 = verifyNotTree checkArrayAssignmentIndices "declare -a foo; foo=(bar)"-prop_checkArrayAssignmentIndices3 = verifyNotTree checkArrayAssignmentIndices "declare -A foo; foo=([i]=bar)"-prop_checkArrayAssignmentIndices4 = verifyTree checkArrayAssignmentIndices "typeset -A foo; foo+=(bar)"-prop_checkArrayAssignmentIndices5 = verifyTree checkArrayAssignmentIndices "arr=( [foo]= bar )"-prop_checkArrayAssignmentIndices6 = verifyTree checkArrayAssignmentIndices "arr=( [foo] = bar )"-prop_checkArrayAssignmentIndices7 = verifyNotTree checkArrayAssignmentIndices "arr=( var=value )"-prop_checkArrayAssignmentIndices8 = verifyNotTree checkArrayAssignmentIndices "arr=( [foo]=bar )"-prop_checkArrayAssignmentIndices9 = verifyNotTree checkArrayAssignmentIndices "arr=( [foo]=\"\" )"-prop_checkArrayAssignmentIndices10 = verifyTree checkArrayAssignmentIndices "declare -A arr; arr=( var=value )"-prop_checkArrayAssignmentIndices11 = verifyTree checkArrayAssignmentIndices "arr=( 1=value )"-prop_checkArrayAssignmentIndices12 = verifyTree checkArrayAssignmentIndices "arr=( $a=value )"-prop_checkArrayAssignmentIndices13 = verifyTree checkArrayAssignmentIndices "arr=( $((1+1))=value )"-checkArrayAssignmentIndices params root =- runNodeAnalysis check params root- where- assocs = getAssociativeArrays root- check _ t =- case t of- T_Assignment _ _ name [] (T_Array _ list) ->- let isAssoc = name `elem` assocs in- mapM_ (checkElement isAssoc) list- _ -> return ()-- checkElement isAssociative t =- case t of- T_IndexedElement _ _ (T_Literal id "") ->- warn id 2192 "This array element has no value. Remove spaces after = or use \"\" for empty string."- T_IndexedElement {} ->- return ()-- T_NormalWord _ parts ->- let literalEquals = do- T_Literal id str <- parts- let (before, after) = break ('=' ==) str- guard $ all isDigit before && not (null after)- return $ warnWithFix id 2191 "The = here is literal. To assign by index, use ( [index]=value ) with no spaces. To keep as literal, quote it." (surroundWith id params "\"")- in- if null literalEquals && isAssociative- then warn (getId t) 2190 "Elements in associative arrays need index, e.g. array=( [index]=value ) ."- else sequence_ literalEquals-- _ -> return ()---prop_checkUnmatchableCases1 = verify checkUnmatchableCases "case foo in bar) true; esac"-prop_checkUnmatchableCases2 = verify checkUnmatchableCases "case foo-$bar in ??|*) true; esac"-prop_checkUnmatchableCases3 = verify checkUnmatchableCases "case foo in foo) true; esac"-prop_checkUnmatchableCases4 = verifyNot checkUnmatchableCases "case foo-$bar in foo*|*bar|*baz*) true; esac"-prop_checkUnmatchableCases5 = verify checkUnmatchableCases "case $f in *.txt) true;; f??.txt) false;; esac"-prop_checkUnmatchableCases6 = verifyNot checkUnmatchableCases "case $f in ?*) true;; *) false;; esac"-prop_checkUnmatchableCases7 = verifyNot checkUnmatchableCases "case $f in $(x)) true;; asdf) false;; esac"-prop_checkUnmatchableCases8 = verify checkUnmatchableCases "case $f in cow) true;; bar|cow) false;; esac"-prop_checkUnmatchableCases9 = verifyNot checkUnmatchableCases "case $f in x) true;;& x) false;; esac"-checkUnmatchableCases params t =- case t of- T_CaseExpression _ word list -> do- -- Check all patterns for whether they can ever match- let allpatterns = concatMap snd3 list- -- Check only the non-fallthrough branches for shadowing- let breakpatterns = concatMap snd3 $ filter (\x -> fst3 x == CaseBreak) list-- if isConstant word- then warn (getId word) 2194- "This word is constant. Did you forget the $ on a variable?"- else mapM_ (check $ wordToPseudoGlob word) allpatterns-- let exactGlobs = tupMap wordToExactPseudoGlob breakpatterns- let fuzzyGlobs = tupMap wordToPseudoGlob breakpatterns- let dominators = zip exactGlobs (tails $ drop 1 fuzzyGlobs)-- mapM_ checkDoms dominators-- _ -> return ()- where- fst3 (x,_,_) = x- snd3 (_,x,_) = x- tp = tokenPositions params- check target candidate = unless (pseudoGlobsCanOverlap target $ wordToPseudoGlob candidate) $- warn (getId candidate) 2195- "This pattern will never match the case statement's word. Double check them."-- tupMap f l = map (\x -> (x, f x)) l- checkDoms ((glob, Just x), rest) =- forM_ (find (\(_, p) -> x `pseudoGlobIsSuperSetof` p) rest) $- \(first,_) -> do- warn (getId glob) 2221 $ "This pattern always overrides a later one" <> patternContext (getId first)- warn (getId first) 2222 $ "This pattern never matches because of a previous pattern" <> patternContext (getId glob)- where- patternContext :: Id -> String- patternContext id =- case posLine . fst <$> Map.lookup id tp of- Just l -> " on line " <> show l <> "."- _ -> "."- checkDoms _ = return ()---prop_checkSubshellAsTest1 = verify checkSubshellAsTest "( -e file )"-prop_checkSubshellAsTest2 = verify checkSubshellAsTest "( 1 -gt 2 )"-prop_checkSubshellAsTest3 = verifyNot checkSubshellAsTest "( grep -c foo bar )"-prop_checkSubshellAsTest4 = verifyNot checkSubshellAsTest "[ 1 -gt 2 ]"-prop_checkSubshellAsTest5 = verify checkSubshellAsTest "( -e file && -x file )"-prop_checkSubshellAsTest6 = verify checkSubshellAsTest "( -e file || -x file && -t 1 )"-prop_checkSubshellAsTest7 = verify checkSubshellAsTest "( ! -d file )"-checkSubshellAsTest _ t =- case t of- T_Subshell id [w] -> check id w- _ -> return ()- where- check id t = case t of- (T_Banged _ w) -> check id w- (T_AndIf _ w _) -> check id w- (T_OrIf _ w _) -> check id w- (T_Pipeline _ _ [T_Redirecting _ _ (T_SimpleCommand _ [] (first:second:_))]) ->- checkParams id first second- _ -> return ()--- checkParams id first second = do- when (maybe False (`elem` unaryTestOps) $ getLiteralString first) $- err id 2204 "(..) is a subshell. Did you mean [ .. ], a test expression?"- when (maybe False (`elem` binaryTestOps) $ getLiteralString second) $- warn id 2205 "(..) is a subshell. Did you mean [ .. ], a test expression?"---prop_checkSplittingInArrays1 = verify checkSplittingInArrays "a=( $var )"-prop_checkSplittingInArrays2 = verify checkSplittingInArrays "a=( $(cmd) )"-prop_checkSplittingInArrays3 = verifyNot checkSplittingInArrays "a=( \"$var\" )"-prop_checkSplittingInArrays4 = verifyNot checkSplittingInArrays "a=( \"$(cmd)\" )"-prop_checkSplittingInArrays5 = verifyNot checkSplittingInArrays "a=( $! $$ $# )"-prop_checkSplittingInArrays6 = verifyNot checkSplittingInArrays "a=( ${#arr[@]} )"-prop_checkSplittingInArrays7 = verifyNot checkSplittingInArrays "a=( foo{1,2} )"-prop_checkSplittingInArrays8 = verifyNot checkSplittingInArrays "a=( * )"-checkSplittingInArrays params t =- case t of- T_Array _ elements -> mapM_ check elements- _ -> return ()- where- check word = case word of- T_NormalWord _ parts -> mapM_ checkPart parts- _ -> return ()- checkPart part = case part of- T_DollarExpansion id _ -> forCommand id- T_DollarBraceCommandExpansion id _ -> forCommand id- T_Backticked id _ -> forCommand id- T_DollarBraced id _ str |- not (isCountingReference part)- && not (isQuotedAlternativeReference part)- && getBracedReference (concat $ oversimplify str) `notElem` variablesWithoutSpaces- -> warn id 2206 $- if shellType params == Ksh- then "Quote to prevent word splitting/globbing, or split robustly with read -A or while read."- else "Quote to prevent word splitting/globbing, or split robustly with mapfile or read -a."- _ -> return ()-- forCommand id =- warn id 2207 $- if shellType params == Ksh- then "Prefer read -A or while read to split command output (or quote to avoid splitting)."- else "Prefer mapfile or read -a to split command output (or quote to avoid splitting)."---prop_checkRedirectionToNumber1 = verify checkRedirectionToNumber "( 1 > 2 )"-prop_checkRedirectionToNumber2 = verify checkRedirectionToNumber "foo 1>2"-prop_checkRedirectionToNumber3 = verifyNot checkRedirectionToNumber "echo foo > '2'"-prop_checkRedirectionToNumber4 = verifyNot checkRedirectionToNumber "foo 1>&2"-checkRedirectionToNumber _ t = case t of- T_IoFile id _ word -> sequence_ $ do- file <- getUnquotedLiteral word- guard $ all isDigit file- return $ warn id 2210 "This is a file redirection. Was it supposed to be a comparison or fd operation?"- _ -> return ()--prop_checkGlobAsCommand1 = verify checkGlobAsCommand "foo*"-prop_checkGlobAsCommand2 = verify checkGlobAsCommand "$(var[i])"-prop_checkGlobAsCommand3 = verifyNot checkGlobAsCommand "echo foo*"-checkGlobAsCommand _ t = case t of- T_SimpleCommand _ _ (first:_)- | isGlob first ->- warn (getId first) 2211 "This is a glob used as a command name. Was it supposed to be in ${..}, array, or is it missing quoting?"- _ -> return ()---prop_checkFlagAsCommand1 = verify checkFlagAsCommand "-e file"-prop_checkFlagAsCommand2 = verify checkFlagAsCommand "foo\n --bar=baz"-prop_checkFlagAsCommand3 = verifyNot checkFlagAsCommand "'--myexec--' args"-prop_checkFlagAsCommand4 = verifyNot checkFlagAsCommand "var=cmd --arg" -- Handled by SC2037-checkFlagAsCommand _ t = case t of- T_SimpleCommand _ [] (first:_)- | isUnquotedFlag first ->- warn (getId first) 2215 "This flag is used as a command name. Bad line break or missing [ .. ]?"- _ -> return ()---prop_checkEmptyCondition1 = verify checkEmptyCondition "if [ ]; then ..; fi"-prop_checkEmptyCondition2 = verifyNot checkEmptyCondition "[ foo -o bar ]"-checkEmptyCondition _ t = case t of- TC_Empty id _ -> style id 2212 "Use 'false' instead of empty [/[[ conditionals."- _ -> return ()--prop_checkPipeToNowhere1 = verify checkPipeToNowhere "foo | echo bar"-prop_checkPipeToNowhere2 = verify checkPipeToNowhere "basename < file.txt"-prop_checkPipeToNowhere3 = verify checkPipeToNowhere "printf 'Lol' <<< str"-prop_checkPipeToNowhere4 = verify checkPipeToNowhere "printf 'Lol' << eof\nlol\neof\n"-prop_checkPipeToNowhere5 = verifyNot checkPipeToNowhere "echo foo | xargs du"-prop_checkPipeToNowhere6 = verifyNot checkPipeToNowhere "ls | echo $(cat)"-prop_checkPipeToNowhere7 = verifyNot checkPipeToNowhere "echo foo | var=$(cat) ls"-prop_checkPipeToNowhere9 = verifyNot checkPipeToNowhere "mv -i f . < /dev/stdin"-prop_checkPipeToNowhere10 = verify checkPipeToNowhere "ls > file | grep foo"-prop_checkPipeToNowhere11 = verify checkPipeToNowhere "ls | grep foo < file"-prop_checkPipeToNowhere12 = verify checkPipeToNowhere "ls > foo > bar"-prop_checkPipeToNowhere13 = verify checkPipeToNowhere "ls > foo 2> bar > baz"-prop_checkPipeToNowhere14 = verify checkPipeToNowhere "ls > foo &> bar"-prop_checkPipeToNowhere15 = verifyNot checkPipeToNowhere "ls > foo 2> bar |& grep 'No space left'"-prop_checkPipeToNowhere16 = verifyNot checkPipeToNowhere "echo World | cat << EOF\nhello $(cat)\nEOF\n"-prop_checkPipeToNowhere17 = verify checkPipeToNowhere "echo World | cat << 'EOF'\nhello $(cat)\nEOF\n"-prop_checkPipeToNowhere18 = verifyNot checkPipeToNowhere "ls 1>&3 3>&1 3>&- | wc -l"-prop_checkPipeToNowhere19 = verifyNot checkPipeToNowhere "find . -print0 | du --files0-from=/dev/stdin"-prop_checkPipeToNowhere20 = verifyNot checkPipeToNowhere "find . | du --exclude-from=/dev/fd/0"--data PipeType = StdoutPipe | StdoutStderrPipe | NoPipe deriving (Eq)-checkPipeToNowhere :: Parameters -> Token -> WriterT [TokenComment] Identity ()-checkPipeToNowhere params t =- case t of- T_Pipeline _ pipes cmds ->- mapM_ checkPipe $ commandsWithContext pipes cmds- T_Redirecting _ redirects cmd | any redirectsStdin redirects -> checkRedir cmd- _ -> return ()- where- checkPipe (input, stage, output) = do- let hasConsumers = hasAdditionalConsumers stage- let hasProducers = hasAdditionalProducers stage-- sequence_ $ do- cmd <- getCommand stage- name <- getCommandBasename cmd- guard $ name `elem` nonReadingCommands- guard $ not hasConsumers && input /= NoPipe- guard . not $ commandSpecificException name cmd-- -- Confusing echo for cat is so common that it's worth a special case- let suggestion =- if name == "echo"- then "Did you want 'cat' instead?"- else "Wrong command or missing xargs?"- return $ warn (getId cmd) 2216 $- "Piping to '" ++ name ++ "', a command that doesn't read stdin. " ++ suggestion-- sequence_ $ do- T_Redirecting _ redirs cmd <- return stage- fds <- mapM getRedirectionFds redirs-- let fdAndToken :: [(Integer, Token)]- fdAndToken =- concatMap (\(list, redir) -> map (\n -> (n, redir)) list) $- zip fds redirs-- let fdMap =- Map.fromListWith (++) $- map (\(a,b) -> (a,[b])) fdAndToken-- let inputWarning = sequence_ $ do- guard $ input /= NoPipe && not hasConsumers- (override:_) <- Map.lookup 0 fdMap- return $ err (getOpId override) 2259 $- "This redirection overrides piped input. To use both, merge or pass filenames."-- -- Only produce output warnings for regular pipes, since these are- -- way more common, and `foo > out 2> err |& foo` can still write- -- to stderr if the files fail to open- let outputWarning = sequence_ $ do- guard $ output == StdoutPipe && not hasProducers- (override:_) <- Map.lookup 1 fdMap- return $ err (getOpId override) 2260 $- "This redirection overrides the output pipe. Use 'tee' to output to both."-- return $ do- inputWarning- outputWarning- mapM_ warnAboutDupes $ Map.assocs fdMap-- commandSpecificException name cmd =- case name of- "du" -> any ((`elem` ["exclude-from", "files0-from"]) . snd) $ getAllFlags cmd- _ -> False-- warnAboutDupes (n, list@(_:_:_)) =- forM_ list $ \c -> err (getOpId c) 2261 $- "Multiple redirections compete for " ++ str n ++ ". Use cat, tee, or pass filenames instead."- warnAboutDupes _ = return ()-- alternative =- if shellType params `elem` [Bash, Ksh]- then "process substitutions or temp files"- else "temporary files"-- str n =- case n of- 0 -> "stdin"- 1 -> "stdout"- 2 -> "stderr"- _ -> "FD " ++ show n-- checkRedir cmd = sequence_ $ do- name <- getCommandBasename cmd- guard $ name `elem` nonReadingCommands- guard . not $ hasAdditionalConsumers cmd- guard . not $ name `elem` ["cp", "mv", "rm"] && cmd `hasFlag` "i"- let suggestion =- if name == "echo"- then "Did you want 'cat' instead?"- else "Bad quoting, wrong command or missing xargs?"- return $ warn (getId cmd) 2217 $- "Redirecting to '" ++ name ++ "', a command that doesn't read stdin. " ++ suggestion-- -- Could any words in a SimpleCommand consume stdin (e.g. echo "$(cat)")?- hasAdditionalConsumers = treeContains mayConsume- -- Could any words in a SimpleCommand produce stdout? E.g. >(tee foo)- hasAdditionalProducers = treeContains mayProduce- treeContains pred t = isNothing $- doAnalysis (guard . not . pred) t-- mayConsume t =- case t of- T_ProcSub _ "<" _ -> True- T_Backticked {} -> True- T_DollarExpansion {} -> True- _ -> False-- mayProduce t =- case t of- T_ProcSub _ ">" _ -> True- _ -> False-- getOpId t =- case t of- T_FdRedirect _ _ x -> getOpId x- T_IoFile _ op _ -> getId op- _ -> getId t-- getRedirectionFds t =- case t of- T_FdRedirect _ "" x -> getDefaultFds x- T_FdRedirect _ "&" _ -> return [1, 2]- T_FdRedirect _ num x | all isDigit num ->- -- Don't report the number unless we know what it is.- -- This avoids triggering on 3>&1 1>&3- getDefaultFds x *> return [read num]- -- Don't bother with {fd}>42 and such- _ -> Nothing-- getDefaultFds redir =- case redir of- T_HereDoc {} -> return [0]- T_HereString {} -> return [0]- T_IoFile _ op _ ->- case op of- T_Less {} -> return [0]- T_Greater {} -> return [1]- T_DGREAT {} -> return [1]- T_GREATAND {} -> return [1, 2]- T_CLOBBER {} -> return [1]- T_IoDuplicate _ op "-" -> getDefaultFds op- _ -> Nothing- _ -> Nothing-- redirectsStdin t =- fromMaybe False $ do- fds <- getRedirectionFds t- return $ 0 `elem` fds-- pipeType t =- case t of- T_Pipe _ "|" -> StdoutPipe- T_Pipe _ "|&" -> StdoutStderrPipe- _ -> NoPipe-- commandsWithContext pipes cmds =- let pipeTypes = map pipeType pipes- inputs = NoPipe : pipeTypes- outputs = pipeTypes ++ [NoPipe]- in- zip3 inputs cmds outputs--prop_checkUseBeforeDefinition1 = verifyTree checkUseBeforeDefinition "f; f() { true; }"-prop_checkUseBeforeDefinition2 = verifyNotTree checkUseBeforeDefinition "f() { true; }; f"-prop_checkUseBeforeDefinition3 = verifyNotTree checkUseBeforeDefinition "if ! mycmd --version; then mycmd() { true; }; fi"-prop_checkUseBeforeDefinition4 = verifyNotTree checkUseBeforeDefinition "mycmd || mycmd() { f; }"-checkUseBeforeDefinition _ t =- execWriter $ evalStateT (mapM_ examine $ revCommands) Map.empty- where- examine t = case t of- T_Pipeline _ _ [T_Redirecting _ _ (T_Function _ _ _ name _)] ->- modify $ Map.insert name t- T_Annotation _ _ w -> examine w- T_Pipeline _ _ cmds -> do- m <- get- unless (Map.null m) $- mapM_ (checkUsage m) $ concatMap recursiveSequences cmds- _ -> return ()-- checkUsage map cmd = sequence_ $ do- name <- getCommandName cmd- def <- Map.lookup name map- return $- err (getId cmd) 2218- "This function is only defined later. Move the definition up."-- revCommands = reverse $ concat $ getCommandSequences t- recursiveSequences x =- let list = concat $ getCommandSequences x in- if null list- then [x]- else concatMap recursiveSequences list--prop_checkForLoopGlobVariables1 = verify checkForLoopGlobVariables "for i in $var/*.txt; do true; done"-prop_checkForLoopGlobVariables2 = verifyNot checkForLoopGlobVariables "for i in \"$var\"/*.txt; do true; done"-prop_checkForLoopGlobVariables3 = verifyNot checkForLoopGlobVariables "for i in $var; do true; done"-checkForLoopGlobVariables _ t =- case t of- T_ForIn _ _ words _ -> mapM_ check words- _ -> return ()- where- check (T_NormalWord _ parts) =- when (any isGlob parts) $- mapM_ suggest $ filter isQuoteableExpansion parts- suggest t = info (getId t) 2231- "Quote expansions in this for loop glob to prevent wordsplitting, e.g. \"$dir\"/*.txt ."---prop_checkSubshelledTests1 = verify checkSubshelledTests "a && ( [ b ] || ! [ c ] )"-prop_checkSubshelledTests2 = verify checkSubshelledTests "( [ a ] )"-prop_checkSubshelledTests3 = verify checkSubshelledTests "( [ a ] && [ b ] || test c )"-prop_checkSubshelledTests4 = verify checkSubshelledTests "( [ a ] && { [ b ] && [ c ]; } )"-prop_checkSubshelledTests5 = verifyNot checkSubshelledTests "( [[ ${var:=x} = y ]] )"-prop_checkSubshelledTests6 = verifyNot checkSubshelledTests "( [[ $((i++)) = 10 ]] )"-prop_checkSubshelledTests7 = verifyNot checkSubshelledTests "( [[ $((i+=1)) = 10 ]] )"-prop_checkSubshelledTests8 = verify checkSubshelledTests "# shellcheck disable=SC2234\nf() ( [[ x ]] )"--checkSubshelledTests params t =- case t of- T_Subshell id list | all isTestStructure list && (not (hasAssignment t)) ->- case () of- -- Special case for if (test) and while (test)- _ | isCompoundCondition (getPath (parentMap params) t) ->- style id 2233 "Remove superfluous (..) around condition to avoid subshell overhead."-- -- Special case for ([ x ]), except for func() ( [ x ] )- _ | isSingleTest list && (not $ isFunctionBody (getPath (parentMap params) t)) ->- style id 2234 "Remove superfluous (..) around test command to avoid subshell overhead."-- -- General case for ([ x ] || [ y ] && etc)- _ -> style id 2235 "Use { ..; } instead of (..) to avoid subshell overhead."- _ -> return ()- where-- isSingleTest cmds =- case cmds of- [c] | isTestCommand c -> True- _ -> False-- isFunctionBody path =- case path of- (_:f:_) -> isFunction f- _ -> False-- isTestStructure t =- case t of- T_Banged _ t -> isTestStructure t- T_AndIf _ a b -> isTestStructure a && isTestStructure b- T_OrIf _ a b -> isTestStructure a && isTestStructure b- T_Pipeline _ [] [T_Redirecting _ _ cmd] ->- case cmd of- T_BraceGroup _ ts -> all isTestStructure ts- T_Subshell _ ts -> all isTestStructure ts- _ -> isTestCommand t- _ -> isTestCommand t-- isTestCommand t =- case t of- T_Pipeline _ [] [T_Redirecting _ _ cmd] ->- case cmd of- T_Condition {} -> True- _ -> cmd `isCommand` "test"- _ -> False-- -- Check if a T_Subshell is used as a condition, e.g. if ( test )- -- This technically also triggers for `if true; then ( test ); fi`- -- but it's still a valid suggestion.- isCompoundCondition chain =- case dropWhile skippable (drop 1 chain) of- T_IfExpression {} : _ -> True- T_WhileExpression {} : _ -> True- T_UntilExpression {} : _ -> True- _ -> False-- hasAssignment t = isNothing $ doAnalysis guardNotAssignment t- guardNotAssignment t =- case t of- TA_Assignment {} -> Nothing- TA_Unary _ s _ -> guard . not $ "++" `isInfixOf` s || "--" `isInfixOf` s- T_DollarBraced _ _ l ->- let str = concat $ oversimplify l- modifier = getBracedModifier str- in- guard . not $ "=" `isPrefixOf` modifier || ":=" `isPrefixOf` modifier- T_DollarBraceCommandExpansion {} -> Nothing- _ -> Just ()-- -- Skip any parent of a T_Subshell until we reach something interesting- skippable t =- case t of- T_Redirecting _ [] _ -> True- T_Pipeline _ [] _ -> True- T_Annotation {} -> True- _ -> False--prop_checkInvertedStringTest1 = verify checkInvertedStringTest "[ ! -z $var ]"-prop_checkInvertedStringTest2 = verify checkInvertedStringTest "! [[ -n $var ]]"-prop_checkInvertedStringTest3 = verifyNot checkInvertedStringTest "! [ -x $var ]"-prop_checkInvertedStringTest4 = verifyNot checkInvertedStringTest "[[ ! -w $var ]]"-prop_checkInvertedStringTest5 = verifyNot checkInvertedStringTest "[ -z $var ]"-checkInvertedStringTest _ t =- case t of- TC_Unary _ _ "!" (TC_Unary _ _ op _) ->- case op of- "-n" -> style (getId t) 2236 "Use -z instead of ! -n."- "-z" -> style (getId t) 2236 "Use -n instead of ! -z."- _ -> return ()- T_Banged _ (T_Pipeline _ _- [T_Redirecting _ _ (T_Condition _ _ (TC_Unary _ _ op _))]) ->- case op of- "-n" -> style (getId t) 2237 "Use [ -z .. ] instead of ! [ -n .. ]."- "-z" -> style (getId t) 2237 "Use [ -n .. ] instead of ! [ -z .. ]."- _ -> return ()- _ -> return ()--prop_checkRedirectionToCommand1 = verify checkRedirectionToCommand "ls > rm"-prop_checkRedirectionToCommand2 = verifyNot checkRedirectionToCommand "ls > 'rm'"-prop_checkRedirectionToCommand3 = verifyNot checkRedirectionToCommand "ls > myfile"-checkRedirectionToCommand _ t =- case t of- T_IoFile _ _ (T_NormalWord id [T_Literal _ str]) | str `elem` commonCommands- && str /= "file" -> -- This would be confusing- warn id 2238 "Redirecting to/from command name instead of file. Did you want pipes/xargs (or quote to ignore)?"- _ -> return ()--prop_checkNullaryExpansionTest1 = verify checkNullaryExpansionTest "[[ $(a) ]]"-prop_checkNullaryExpansionTest2 = verify checkNullaryExpansionTest "[[ $a ]]"-prop_checkNullaryExpansionTest3 = verifyNot checkNullaryExpansionTest "[[ $a=1 ]]"-prop_checkNullaryExpansionTest4 = verifyNot checkNullaryExpansionTest "[[ -n $(a) ]]"-prop_checkNullaryExpansionTest5 = verify checkNullaryExpansionTest "[[ \"$a$b\" ]]"-prop_checkNullaryExpansionTest6 = verify checkNullaryExpansionTest "[[ `x` ]]"-checkNullaryExpansionTest params t =- case t of- TC_Nullary _ _ word ->- case getWordParts word of- [t] | isCommandSubstitution t ->- styleWithFix id 2243 "Prefer explicit -n to check for output (or run command without [/[[ to check for success)." fix-- -- If they're constant, you get SC2157 &co- x | all (not . isConstant) x ->- styleWithFix id 2244 "Prefer explicit -n to check non-empty string (or use =/-ne to check boolean/integer)." fix- _ -> return ()- where- id = getId word- fix = fixWith [replaceStart id params 0 "-n "]- _ -> return ()---prop_checkDollarQuoteParen1 = verify checkDollarQuoteParen "$\"(foo)\""-prop_checkDollarQuoteParen2 = verify checkDollarQuoteParen "$\"{foo}\""-prop_checkDollarQuoteParen3 = verifyNot checkDollarQuoteParen "\"$(foo)\""-prop_checkDollarQuoteParen4 = verifyNot checkDollarQuoteParen "$\"..\""-checkDollarQuoteParen params t =- case t of- T_DollarDoubleQuoted id ((T_Literal _ (c:_)):_) | c `elem` "({" ->- warnWithFix id 2247 "Flip leading $ and \" if this should be a quoted substitution." (fix id)- _ -> return ()- where- fix id = fixWith [replaceStart id params 2 "\"$"]--prop_checkTranslatedStringVariable1 = verify checkTranslatedStringVariable "foo_bar2=val; $\"foo_bar2\""-prop_checkTranslatedStringVariable2 = verifyNot checkTranslatedStringVariable "$\"foo_bar2\""-prop_checkTranslatedStringVariable3 = verifyNot checkTranslatedStringVariable "$\"..\""-prop_checkTranslatedStringVariable4 = verifyNot checkTranslatedStringVariable "var=val; $\"$var\""-prop_checkTranslatedStringVariable5 = verifyNot checkTranslatedStringVariable "foo=var; bar=val2; $\"foo bar\""-checkTranslatedStringVariable params (T_DollarDoubleQuoted id [T_Literal _ s])- | all isVariableChar s- && Map.member s assignments- = warnWithFix id 2256 "This translated string is the name of a variable. Flip leading $ and \" if this should be a quoted substitution." (fix id)- where- assignments = foldl (flip ($)) Map.empty (map insertAssignment $ variableFlow params)- insertAssignment (Assignment (_, token, name, _)) | isVariableName name =- Map.insert name token- insertAssignment _ = Prelude.id- fix id = fixWith [replaceStart id params 2 "\"$"]-checkTranslatedStringVariable _ _ = return ()--prop_checkDefaultCase1 = verify checkDefaultCase "case $1 in a) true ;; esac"-prop_checkDefaultCase2 = verify checkDefaultCase "case $1 in ?*?) true ;; *? ) true ;; esac"-prop_checkDefaultCase3 = verifyNot checkDefaultCase "case $1 in x|*) true ;; esac"-prop_checkDefaultCase4 = verifyNot checkDefaultCase "case $1 in **) true ;; esac"-checkDefaultCase _ t =- case t of- T_CaseExpression id _ list ->- unless (any canMatchAny list) $- info id 2249 "Consider adding a default *) case, even if it just exits with error."- _ -> return ()- where- canMatchAny (_, list, _) = any canMatchAny' list- -- hlint objects to 'pattern' as a variable name- canMatchAny' pat = fromMaybe False $ do- pg <- wordToExactPseudoGlob pat- return $ pseudoGlobIsSuperSetof pg [PGMany]--prop_checkUselessBang1 = verify checkUselessBang "set -e; ! true; rest"-prop_checkUselessBang2 = verifyNot checkUselessBang "! true; rest"-prop_checkUselessBang3 = verify checkUselessBang "set -e; while true; do ! true; done"-prop_checkUselessBang4 = verifyNot checkUselessBang "set -e; if ! true; then true; fi"-prop_checkUselessBang5 = verifyNot checkUselessBang "set -e; ( ! true )"-prop_checkUselessBang6 = verify checkUselessBang "set -e; { ! true; }"-prop_checkUselessBang7 = verifyNot checkUselessBang "set -e; x() { ! [ x ]; }"-prop_checkUselessBang8 = verifyNot checkUselessBang "set -e; if { ! true; }; then true; fi"-prop_checkUselessBang9 = verifyNot checkUselessBang "set -e; while ! true; do true; done"-checkUselessBang params t = when (hasSetE params) $ mapM_ check (getNonReturningCommands t)- where- check t =- case t of- T_Banged id cmd | not $ isCondition (getPath (parentMap params) t) ->- addComment $ makeCommentWithFix InfoC id 2251- "This ! is not on a condition and skips errexit. Use `&& exit 1` instead, or make sure $? is checked."- (fixWith [replaceStart id params 1 "", replaceEnd (getId cmd) params 0 " && exit 1"])- _ -> return ()-- -- Get all the subcommands that aren't likely to be the return value- getNonReturningCommands :: Token -> [Token]- getNonReturningCommands t =- case t of- T_Script _ _ list -> dropLast list- T_BraceGroup _ list -> if isFunctionBody t then dropLast list else list- T_Subshell _ list -> dropLast list- T_WhileExpression _ conds cmds -> dropLast conds ++ cmds- T_UntilExpression _ conds cmds -> dropLast conds ++ cmds- T_ForIn _ _ _ list -> list- T_ForArithmetic _ _ _ _ list -> list- T_Annotation _ _ t -> getNonReturningCommands t- T_IfExpression _ conds elses ->- concatMap (dropLast . fst) conds ++ concatMap snd conds ++ elses- _ -> []-- isFunctionBody t =- case getPath (parentMap params) t of- _:T_Function {}:_-> True- _ -> False-- dropLast t =- case t of- [_] -> []- x:rest -> x : dropLast rest- _ -> []--prop_checkModifiedArithmeticInRedirection1 = verify checkModifiedArithmeticInRedirection "ls > $((i++))"-prop_checkModifiedArithmeticInRedirection2 = verify checkModifiedArithmeticInRedirection "cat < \"foo$((i++)).txt\""-prop_checkModifiedArithmeticInRedirection3 = verifyNot checkModifiedArithmeticInRedirection "while true; do true; done > $((i++))"-prop_checkModifiedArithmeticInRedirection4 = verify checkModifiedArithmeticInRedirection "cat <<< $((i++))"-prop_checkModifiedArithmeticInRedirection5 = verify checkModifiedArithmeticInRedirection "cat << foo\n$((i++))\nfoo\n"-prop_checkModifiedArithmeticInRedirection6 = verifyNot checkModifiedArithmeticInRedirection "#!/bin/dash\nls > $((i=i+1))"-checkModifiedArithmeticInRedirection params t = unless (shellType params == Dash) $- case t of- T_Redirecting _ redirs (T_SimpleCommand _ _ (_:_)) -> mapM_ checkRedirs redirs- _ -> return ()- where- checkRedirs t =- case t of- T_FdRedirect _ _ (T_IoFile _ _ word) ->- mapM_ checkArithmetic $ getWordParts word- T_FdRedirect _ _ (T_HereString _ word) ->- mapM_ checkArithmetic $ getWordParts word- T_FdRedirect _ _ (T_HereDoc _ _ _ _ list) ->- mapM_ checkArithmetic list- _ -> return ()- checkArithmetic t =- case t of- T_DollarArithmetic _ x -> checkModifying x- _ -> return ()- checkModifying t =- case t of- TA_Sequence _ list -> mapM_ checkModifying list- TA_Unary id s _ | s `elem` ["|++", "++|", "|--", "--|"] -> warnFor id- TA_Assignment id _ _ _ -> warnFor id- TA_Binary _ _ x y -> mapM_ checkModifying [x ,y]- TA_Trinary _ x y z -> mapM_ checkModifying [x, y, z]- _ -> return ()- warnFor id =- warn id 2257 "Arithmetic modifications in command redirections may be discarded. Do them separately."--prop_checkAliasUsedInSameParsingUnit1 = verifyTree checkAliasUsedInSameParsingUnit "alias x=y; x"-prop_checkAliasUsedInSameParsingUnit2 = verifyNotTree checkAliasUsedInSameParsingUnit "alias x=y\nx"-prop_checkAliasUsedInSameParsingUnit3 = verifyTree checkAliasUsedInSameParsingUnit "{ alias x=y\nx\n}"-prop_checkAliasUsedInSameParsingUnit4 = verifyNotTree checkAliasUsedInSameParsingUnit "alias x=y; 'x';"-prop_checkAliasUsedInSameParsingUnit5 = verifyNotTree checkAliasUsedInSameParsingUnit ":\n{\n#shellcheck disable=SC2262\nalias x=y\nx\n}"-prop_checkAliasUsedInSameParsingUnit6 = verifyNotTree checkAliasUsedInSameParsingUnit ":\n{\n#shellcheck disable=SC2262\nalias x=y\nalias x=z\nx\n}" -- Only consider the first instance-checkAliasUsedInSameParsingUnit :: Parameters -> Token -> [TokenComment]-checkAliasUsedInSameParsingUnit params root =- let- -- Get all root commands- commands = concat $ getCommandSequences root- -- Group them by whether they start on the same line where the previous one ended- units = groupByLink followsOnLine commands- in- execWriter $ mapM_ checkUnit units- where- lineSpan t =- let m = tokenPositions params in do- (start, end) <- Map.lookup t m- return $ (posLine start, posLine end)-- followsOnLine a b = fromMaybe False $ do- (_, end) <- lineSpan (getId a)- (start, _) <- lineSpan (getId b)- return $ end == start-- checkUnit :: [Token] -> Writer [TokenComment] ()- checkUnit unit = evalStateT (mapM_ (doAnalysis findCommands) unit) (Map.empty)-- findCommands :: Token -> StateT (Map.Map String Token) (Writer [TokenComment]) ()- findCommands t = case t of- T_SimpleCommand _ _ (cmd:args) ->- case getUnquotedLiteral cmd of- Just "alias" ->- mapM_ addAlias args- Just name | '/' `notElem` name -> do- cmd <- gets (Map.lookup name)- case cmd of- Just alias ->- unless (isSourced params t || shouldIgnoreCode params 2262 alias) $ do- warn (getId alias) 2262 "This alias can't be defined and used in the same parsing unit. Use a function instead."- info (getId t) 2263 "Since they're in the same parsing unit, this command will not refer to the previously mentioned alias."- _ -> return ()- _ -> return ()- _ -> return ()- addAlias arg = do- let (name, value) = break (== '=') $ getLiteralStringDef "-" arg- when (isVariableName name && not (null value)) $- modify (Map.insertWith (\new old -> old) name arg)--isSourced params t =- let- f (T_SourceCommand {}) = True- f _ = False- in- any f $ getPath (parentMap params) t----- Like groupBy, but compares pairs of adjacent elements, rather than against the first of the span-prop_groupByLink1 = groupByLink (\a b -> a+1 == b) [1,2,3,2,3,7,8,9] == [[1,2,3], [2,3], [7,8,9]]-prop_groupByLink2 = groupByLink (==) ([] :: [()]) == []-groupByLink :: (a -> a -> Bool) -> [a] -> [[a]]-groupByLink f list =- case list of- [] -> []- (x:xs) -> foldr c n xs x []- where- c next rest current span =- if f current next- then rest next (current:span)- else (reverse $ current:span) : rest next []- n current span = [reverse (current:span)]---prop_checkBlatantRecursion1 = verify checkBlatantRecursion ":(){ :|:& };:"-prop_checkBlatantRecursion2 = verify checkBlatantRecursion "f() { f; }"-prop_checkBlatantRecursion3 = verifyNot checkBlatantRecursion "f() { command f; }"-prop_checkBlatantRecursion4 = verify checkBlatantRecursion "cd() { cd \"$lol/$1\" || exit; }"-prop_checkBlatantRecursion5 = verifyNot checkBlatantRecursion "cd() { [ -z \"$1\" ] || cd \"$1\"; }"-prop_checkBlatantRecursion6 = verifyNot checkBlatantRecursion "cd() { something; cd $1; }"-prop_checkBlatantRecursion7 = verifyNot checkBlatantRecursion "cd() { builtin cd $1; }"-checkBlatantRecursion :: Parameters -> Token -> Writer [TokenComment] ()-checkBlatantRecursion params t =- case t of- T_Function _ _ _ name body ->- case getCommandSequences body of- [first : _] -> checkList name first- _ -> return ()- _ -> return ()- where- checkList :: String -> Token -> Writer [TokenComment] ()- checkList name t =- case t of- T_Backgrounded _ t -> checkList name t- T_AndIf _ lhs _ -> checkList name lhs- T_OrIf _ lhs _ -> checkList name lhs- T_Pipeline _ _ cmds -> mapM_ (checkCommand name) cmds- _ -> return ()-- checkCommand :: String -> Token -> Writer [TokenComment] ()- checkCommand name cmd = sequence_ $ do- let (invokedM, t) = getCommandNameAndToken True cmd- invoked <- invokedM- guard $ name == invoked- return $- errWithFix (getId t) 2264- ("This function unconditionally re-invokes itself. Missing 'command'?")- (fixWith [replaceStart (getId t) params 0 $ "command "])---prop_checkBadTestAndOr1 = verify checkBadTestAndOr "[ x ] & [ y ]"-prop_checkBadTestAndOr2 = verify checkBadTestAndOr "test -e foo & [ y ]"-prop_checkBadTestAndOr3 = verify checkBadTestAndOr "[ x ] | [ y ]"-checkBadTestAndOr params t =- case t of- T_Pipeline _ seps cmds@(_:_:_) -> checkOrs seps cmds- T_Backgrounded id cmd -> checkAnds id cmd- _ -> return ()- where- checkOrs seps cmds =- let maybeSeps = map Just seps- commandWithSeps = zip3 (Nothing:maybeSeps) cmds (maybeSeps ++ [Nothing])- in- mapM_ checkTest commandWithSeps- checkTest (before, cmd, after) =- when (isTest cmd) $ do- checkPipe before- checkPipe after-- checkPipe t =- case t of- Just (T_Pipe id "|") ->- warnWithFix id 2266 "Use || for logical OR. Single | will pipe." $- fixWith [replaceEnd id params 0 "|"]- _ -> return ()-- checkAnds id t =- case t of- T_AndIf _ _ rhs -> checkAnds id rhs- T_OrIf _ _ rhs -> checkAnds id rhs- T_Pipeline _ _ list | not (null list) -> checkAnds id (last list)- cmd -> when (isTest cmd) $- errWithFix id 2265 "Use && for logical AND. Single & will background and return true." $- (fixWith [replaceEnd id params 0 "&"])-- isTest t =- case t of- T_Condition {} -> True- T_SimpleCommand {} -> t `isCommand` "test"- T_Redirecting _ _ t -> isTest t- T_Annotation _ _ t -> isTest t- _ -> False--prop_checkComparisonWithLeadingX1 = verify checkComparisonWithLeadingX "[ x$foo = xlol ]"-prop_checkComparisonWithLeadingX2 = verify checkComparisonWithLeadingX "test x$foo = xlol"-prop_checkComparisonWithLeadingX3 = verifyNot checkComparisonWithLeadingX "[ $foo = xbar ]"-prop_checkComparisonWithLeadingX4 = verifyNot checkComparisonWithLeadingX "test $foo = xbar"-prop_checkComparisonWithLeadingX5 = verify checkComparisonWithLeadingX "[ \"x$foo\" = 'xlol' ]"-prop_checkComparisonWithLeadingX6 = verify checkComparisonWithLeadingX "[ x\"$foo\" = x'lol' ]"-checkComparisonWithLeadingX params t =- case t of- TC_Binary id typ op lhs rhs | op == "=" || op == "==" ->- check lhs rhs- T_SimpleCommand _ _ [cmd, lhs, op, rhs] |- getLiteralString cmd == Just "test" &&- getLiteralString op `elem` [Just "=", Just "=="] ->- check lhs rhs- _ -> return ()- where- msg = "Avoid x-prefix in comparisons as it no longer serves a purpose."- check lhs rhs = sequence_ $ do- l <- fixLeadingX lhs- r <- fixLeadingX rhs- return $ styleWithFix (getId lhs) 2268 msg $ fixWith [l, r]-- fixLeadingX token =- case getWordParts token of- T_Literal id ('x':_):_ ->- case token of- -- The side is a single, unquoted x, so we have to quote- T_NormalWord _ [T_Literal id "x"] ->- return $ replaceStart id params 1 "\"\""- -- Otherwise we can just delete it- _ -> return $ replaceStart id params 1 ""- T_SingleQuoted id ('x':_):_ ->- -- Replace the single quote and x- return $ replaceStart id params 2 "'"- _ -> Nothing--prop_checkAssignToSelf1 = verify checkAssignToSelf "x=$x"-prop_checkAssignToSelf2 = verify checkAssignToSelf "x=${x}"-prop_checkAssignToSelf3 = verify checkAssignToSelf "x=\"$x\""-prop_checkAssignToSelf4 = verifyNot checkAssignToSelf "x=$x mycmd"-checkAssignToSelf _ t =- case t of- T_SimpleCommand _ vars [] -> mapM_ check vars- _ -> return ()- where- check t =- case t of- T_Assignment id Assign name [] t ->- case getWordParts t of- [T_DollarBraced _ _ b] -> do- when (Just name == getLiteralString b) $- msg id- _ -> return ()- _ -> return ()- msg id = info id 2269 "This variable is assigned to itself, so the assignment does nothing."---prop_checkEqualsInCommand1a = verifyCodes checkEqualsInCommand [2277] "#!/bin/bash\n0='foo'"-prop_checkEqualsInCommand2a = verifyCodes checkEqualsInCommand [2278] "#!/bin/ksh \n$0='foo'"-prop_checkEqualsInCommand3a = verifyCodes checkEqualsInCommand [2279] "#!/bin/dash\n${0}='foo'"-prop_checkEqualsInCommand4a = verifyCodes checkEqualsInCommand [2280] "#!/bin/sh \n0='foo'"--prop_checkEqualsInCommand1b = verifyCodes checkEqualsInCommand [2270] "1='foo'"-prop_checkEqualsInCommand2b = verifyCodes checkEqualsInCommand [2270] "${2}='foo'"--prop_checkEqualsInCommand1c = verifyCodes checkEqualsInCommand [2271] "var$((n+1))=value"-prop_checkEqualsInCommand2c = verifyCodes checkEqualsInCommand [2271] "var${x}=value"-prop_checkEqualsInCommand3c = verifyCodes checkEqualsInCommand [2271] "var$((cmd))x='foo'"-prop_checkEqualsInCommand4c = verifyCodes checkEqualsInCommand [2271] "$(cmd)='foo'"--prop_checkEqualsInCommand1d = verifyCodes checkEqualsInCommand [2273] "======="-prop_checkEqualsInCommand2d = verifyCodes checkEqualsInCommand [2274] "======= Here ======="-prop_checkEqualsInCommand3d = verifyCodes checkEqualsInCommand [2275] "foo\n=42"--prop_checkEqualsInCommand1e = verifyCodes checkEqualsInCommand [] "--foo=bar"-prop_checkEqualsInCommand2e = verifyCodes checkEqualsInCommand [] "$(cmd)'=foo'"-prop_checkEqualsInCommand3e = verifyCodes checkEqualsInCommand [2276] "var${x}/=value"-prop_checkEqualsInCommand4e = verifyCodes checkEqualsInCommand [2276] "${}=value"-prop_checkEqualsInCommand5e = verifyCodes checkEqualsInCommand [2276] "${#x}=value"--prop_checkEqualsInCommand1f = verifyCodes checkEqualsInCommand [2281] "$var=foo"-prop_checkEqualsInCommand2f = verifyCodes checkEqualsInCommand [2281] "$a=$b"-prop_checkEqualsInCommand3f = verifyCodes checkEqualsInCommand [2281] "${var}=foo"-prop_checkEqualsInCommand4f = verifyCodes checkEqualsInCommand [2281] "${var[42]}=foo"-prop_checkEqualsInCommand5f = verifyCodes checkEqualsInCommand [2281] "$var+=foo"--prop_checkEqualsInCommand1g = verifyCodes checkEqualsInCommand [2282] "411toppm=true"--checkEqualsInCommand params originalToken =- case originalToken of- T_SimpleCommand _ _ (word:_) -> check word- _ -> return ()- where- hasEquals t =- case t of- T_Literal _ s -> '=' `elem` s- _ -> False-- check t@(T_NormalWord _ list) | any hasEquals list =- case break hasEquals list of- (leading, (eq:_)) -> msg t (stripSinglePlus leading) eq- _ -> return ()- check _ = return ()-- -- This is a workaround for the parser adding + and = as separate literals- stripSinglePlus l =- case reverse l of- (T_Literal _ "+"):rest -> reverse rest- _ -> l-- positionalAssignmentRe = mkRegex "^[0-9][0-9]?="- positionalMsg id =- err id 2270 "To assign positional parameters, use 'set -- first second ..' (or use [ ] to compare)."- indirectionMsg id =- err id 2271 "For indirection, use arrays, declare \"var$n=value\", or (for sh) read/eval."- badComparisonMsg id =- err id 2272 "Command name contains ==. For comparison, use [ \"$var\" = value ]."- conflictMarkerMsg id =- err id 2273 "Sequence of ===s found. Merge conflict or intended as a commented border?"- borderMsg id =- err id 2274 "Command name starts with ===. Intended as a commented border?"- prefixMsg id =- err id 2275 "Command name starts with =. Bad line break?"- genericMsg id =- err id 2276 "This is interpreted as a command name containing '='. Bad assignment or comparison?"- assign0Msg id bashfix =- case shellType params of- Bash -> errWithFix id 2277 "Use BASH_ARGV0 to assign to $0 in bash (or use [ ] to compare)." bashfix- Ksh -> err id 2278 "$0 can't be assigned in Ksh (but it does reflect the current function)."- Dash -> err id 2279 "$0 can't be assigned in Dash. This becomes a command name."- _ -> err id 2280 "$0 can't be assigned this way, and there is no portable alternative."- leadingNumberMsg id =- err id 2282 "Variable names can't start with numbers, so this is interpreted as a command."-- isExpansion t =- case t of- T_Arithmetic {} -> True- _ -> isQuoteableExpansion t-- isConflictMarker cmd = fromMaybe False $ do- str <- getUnquotedLiteral cmd- guard $ all (== '=') str- guard $ length str >= 4 && length str <= 12 -- Git uses 7 but who knows- return True-- mayBeVariableName l = fromMaybe False $ do- guard . not $ any isQuotes l- guard . not $ any willBecomeMultipleArgs l- str <- getLiteralStringExt (\_ -> Just "x") (T_NormalWord (Id 0) l)- return $ isVariableName str-- isLeadingNumberVar s =- let lead = takeWhile (/= '=') s- in not (null lead) && isDigit (head lead)- && all isVariableChar lead && not (all isDigit lead)-- msg cmd leading (T_Literal litId s) = do- -- There are many different cases, and the order of the branches matter.- case leading of- -- --foo=42- [] | "-" `isPrefixOf` s -> -- There's SC2215 for these- return ()-- -- ======Hello======- [] | "=" `isPrefixOf` s ->- case originalToken of- T_SimpleCommand _ [] [word] | isConflictMarker word ->- conflictMarkerMsg (getId originalToken)- _ | "===" `isPrefixOf` s -> borderMsg (getId originalToken)- _ -> prefixMsg (getId cmd)-- -- '$var==42'- _ | "==" `isInfixOf` s ->- badComparisonMsg (getId cmd)-- -- '${foo[x]}=42' and '$foo=42'- [T_DollarBraced id braced l] | "=" `isPrefixOf` s -> do- let variableStr = concat $ oversimplify l- let variableReference = getBracedReference variableStr- let variableModifier = getBracedModifier variableStr- let isPlain = isVariableName variableStr- let isPositional = all isDigit variableStr-- let isArray = variableReference /= ""- && "[" `isPrefixOf` variableModifier- && "]" `isSuffixOf` variableModifier-- case () of- -- '$foo=bar' should already have caused a parse-time SC1066- -- _ | not braced && isPlain ->- -- return ()-- _ | variableStr == "" -> -- Don't try to fix ${}=foo- genericMsg (getId cmd)-- -- '$#=42' or '${#var}=42'- _ | "#" `isPrefixOf` variableStr ->- genericMsg (getId cmd)-- -- '${0}=42'- _ | variableStr == "0" ->- assign0Msg id $ fixWith [replaceToken id params "BASH_ARGV0"]-- -- '$2=2'- _ | isPositional ->- positionalMsg id-- _ | isArray || isPlain ->- errWithFix id 2281- ("Don't use " ++ (if braced then "${}" else "$") ++ " on the left side of assignments.") $- fixWith $- if braced- then [ replaceStart id params 2 "", replaceEnd id params 1 "" ]- else [ replaceStart id params 1 "" ]-- _ -> indirectionMsg id-- -- 2=42- [] | s `matches` positionalAssignmentRe ->- if "0=" `isPrefixOf` s- then- assign0Msg litId $ fixWith [replaceStart litId params 1 "BASH_ARGV0"]- else- positionalMsg litId-- -- 9foo=42- [] | isLeadingNumberVar s ->- leadingNumberMsg (getId cmd)-- -- var${foo}x=42- (_:_) | mayBeVariableName leading && (all isVariableChar $ takeWhile (/= '=') s) ->- indirectionMsg (getId cmd)-- _ -> genericMsg (getId cmd)---prop_checkSecondArgIsComparison1 = verify checkSecondArgIsComparison "foo = $bar"-prop_checkSecondArgIsComparison2 = verify checkSecondArgIsComparison "$foo = $bar"-prop_checkSecondArgIsComparison3 = verify checkSecondArgIsComparison "2f == $bar"-prop_checkSecondArgIsComparison4 = verify checkSecondArgIsComparison "'var' =$bar"-prop_checkSecondArgIsComparison5 = verify checkSecondArgIsComparison "foo ='$bar'"-prop_checkSecondArgIsComparison6 = verify checkSecondArgIsComparison "$foo =$bar"-prop_checkSecondArgIsComparison7 = verify checkSecondArgIsComparison "2f ==$bar"-prop_checkSecondArgIsComparison8 = verify checkSecondArgIsComparison "'var' =$bar"-prop_checkSecondArgIsComparison9 = verify checkSecondArgIsComparison "var += $(foo)"-prop_checkSecondArgIsComparison10 = verify checkSecondArgIsComparison "var +=$(foo)"-checkSecondArgIsComparison _ t =- case t of- T_SimpleCommand _ _ (lhs:arg:_) -> sequence_ $ do- argString <- getLeadingUnquotedString arg- case argString of- '=':'=':'=':'=':_ -> Nothing -- Don't warn about `echo ======` and such- '+':'=':_ ->- return $ err (headId t) 2285 $- "Remove spaces around += to assign (or quote '+=' if literal)."- '=':'=':_ ->- return $ err (getId t) 2284 $- "Use [ x = y ] to compare values (or quote '==' if literal)."- '=':_ ->- return $ err (headId arg) 2283 $- "Remove spaces around = to assign (or use [ ] to compare, or quote '=' if literal)."- _ -> Nothing- _ -> return ()- where- -- We don't pinpoint exactly, but this helps cases like foo =$bar- headId t =- case t of- T_NormalWord _ (x:_) -> getId x- _ -> getId t---prop_checkCommandWithTrailingSymbol1 = verify checkCommandWithTrailingSymbol "/"-prop_checkCommandWithTrailingSymbol2 = verify checkCommandWithTrailingSymbol "/foo/ bar/baz"-prop_checkCommandWithTrailingSymbol3 = verify checkCommandWithTrailingSymbol "/"-prop_checkCommandWithTrailingSymbol4 = verifyNot checkCommandWithTrailingSymbol "/*"-prop_checkCommandWithTrailingSymbol5 = verifyNot checkCommandWithTrailingSymbol "$foo/$bar"-prop_checkCommandWithTrailingSymbol6 = verify checkCommandWithTrailingSymbol "foo, bar"-prop_checkCommandWithTrailingSymbol7 = verifyNot checkCommandWithTrailingSymbol ". foo.sh"-prop_checkCommandWithTrailingSymbol8 = verifyNot checkCommandWithTrailingSymbol ": foo"-prop_checkCommandWithTrailingSymbol9 = verifyNot checkCommandWithTrailingSymbol "/usr/bin/python[23] file.py"--checkCommandWithTrailingSymbol _ t =- case t of- T_SimpleCommand _ _ (cmd:_) ->- let str = fromJust $ getLiteralStringExt (\_ -> Just "x") cmd- last = lastOrDefault 'x' str- in- case str of- "." -> return () -- The . command- ":" -> return () -- The : command- " " -> return () -- Probably caught by SC1101- "//" -> return () -- Probably caught by SC1127- "" -> err (getId cmd) 2286 "This empty string is interpreted as a command name. Double check syntax (or use 'true' as a no-op)."- _ | last == '/' -> err (getId cmd) 2287 "This is interpreted as a command name ending with '/'. Double check syntax."- _ | last `elem` "\\.,([{<>}])#\"\'% " -> warn (getId cmd) 2288 ("This is interpreted as a command name ending with " ++ (format last) ++ ". Double check syntax.")- _ | '\t' `elem` str -> err (getId cmd) 2289 "This is interpreted as a command name containing a tab. Double check syntax."- _ | '\n' `elem` str -> err (getId cmd) 2289 "This is interpreted as a command name containing a linefeed. Double check syntax."- _ -> return ()- _ -> return ()- where- format x =- case x of- ' ' -> "space"- '\'' -> "apostrophe"- '\"' -> "doublequote"- x -> '\'' : x : "\'"---prop_checkRequireDoubleBracket1 = verifyTree checkRequireDoubleBracket "[ -x foo ]"-prop_checkRequireDoubleBracket2 = verifyTree checkRequireDoubleBracket "[ foo -o bar ]"-prop_checkRequireDoubleBracket3 = verifyNotTree checkRequireDoubleBracket "#!/bin/sh\n[ -x foo ]"-prop_checkRequireDoubleBracket4 = verifyNotTree checkRequireDoubleBracket "[[ -x foo ]]"-checkRequireDoubleBracket params =- if isBashLike params- then nodeChecksToTreeCheck [check] params- else const []- where- check _ t = case t of- T_Condition id SingleBracket _ ->- styleWithFix id 2292 "Prefer [[ ]] over [ ] for tests in Bash/Ksh." (fixFor t)- _ -> return ()-- fixFor t = fixWith $- if isSimple t- then- [- replaceStart (getId t) params 0 "[",- replaceEnd (getId t) params 0 "]"- ]- else []-- -- We don't tag operators like < and -o well enough to replace them,- -- so just handle the simple cases.- isSimple t = case t of- T_Condition _ _ s -> isSimple s- TC_Binary _ _ op _ _ -> not $ any (\x -> x `elem` op) "<>"- TC_Unary {} -> True- TC_Nullary {} -> True- _ -> False---prop_checkUnquotedParameterExpansionPattern1 = verify checkUnquotedParameterExpansionPattern "echo \"${var#$x}\""-prop_checkUnquotedParameterExpansionPattern2 = verify checkUnquotedParameterExpansionPattern "echo \"${var%%$(x)}\""-prop_checkUnquotedParameterExpansionPattern3 = verifyNot checkUnquotedParameterExpansionPattern "echo \"${var[#$x]}\""-prop_checkUnquotedParameterExpansionPattern4 = verifyNot checkUnquotedParameterExpansionPattern "echo \"${var%\"$x\"}\""--checkUnquotedParameterExpansionPattern params x =- case x of- T_DollarBraced _ True word@(T_NormalWord _ (T_Literal _ s : rest@(_:_))) -> do- let modifier = getBracedModifier $ concat $ oversimplify word- when ("%" `isPrefixOf` modifier || "#" `isPrefixOf` modifier) $- mapM_ check rest- _ -> return ()- where- check t =- case t of- T_DollarBraced {} -> inform t- T_DollarExpansion {} -> inform t- T_Backticked {} -> inform t- _ -> return ()-- inform t =- infoWithFix (getId t) 2295- "Expansions inside ${..} need to be quoted separately, otherwise they match as patterns." $- surroundWith (getId t) params "\""---prop_checkArrayValueUsedAsIndex1 = verifyTree checkArrayValueUsedAsIndex "for i in ${arr[@]}; do echo ${arr[i]}; done"-prop_checkArrayValueUsedAsIndex2 = verifyTree checkArrayValueUsedAsIndex "for i in ${arr[@]}; do echo ${arr[$i]}; done"-prop_checkArrayValueUsedAsIndex3 = verifyTree checkArrayValueUsedAsIndex "for i in ${arr[@]}; do echo $((arr[i])); done"-prop_checkArrayValueUsedAsIndex4 = verifyTree checkArrayValueUsedAsIndex "for i in ${arr1[@]} ${arr2[@]}; do echo ${arr1[$i]}; done"-prop_checkArrayValueUsedAsIndex5 = verifyTree checkArrayValueUsedAsIndex "for i in ${arr1[@]} ${arr2[@]}; do echo ${arr2[$i]}; done"-prop_checkArrayValueUsedAsIndex7 = verifyNotTree checkArrayValueUsedAsIndex "for i in ${arr[@]}; do echo ${arr[K]}; done"-prop_checkArrayValueUsedAsIndex8 = verifyNotTree checkArrayValueUsedAsIndex "for i in ${arr[@]}; do i=42; echo ${arr[i]}; done"-prop_checkArrayValueUsedAsIndex9 = verifyNotTree checkArrayValueUsedAsIndex "for i in ${arr[@]}; do echo ${arr2[i]}; done"--checkArrayValueUsedAsIndex params _ =- doVariableFlowAnalysis read write Map.empty (variableFlow params)- where- write loop@T_ForIn {} _ name (DataString (SourceFrom words)) = do- modify $ Map.insert name (loop, mapMaybe f words)- return []- where- f x = do- name <- getArrayName x- return (x, name)-- write _ _ name _ = do- modify $ Map.delete name- return []-- read _ t name = do- varMap <- get- return $ fromMaybe [] $ do- (loop, arrays) <- Map.lookup name varMap- (arrayRef, arrayName) <- getArrayIfUsedAsIndex name t- -- Is this one of the 'for' arrays?- (loopWord, _) <- find ((==arrayName) . snd) arrays- -- Are we still in this loop?- guard $ getId loop `elem` map getId (getPath parents t)- return [- makeComment WarningC (getId loopWord) 2302 "This loops over values. To loop over keys, use \"${!array[@]}\".",- makeComment WarningC (getId arrayRef) 2303 $ (e4m name) ++ " is an array value, not a key. Use directly or loop over keys instead."- ]-- parents = parentMap params-- getArrayName :: Token -> Maybe String- getArrayName t = do- [T_DollarBraced _ _ l] <- return $ getWordParts t- let str = concat $ oversimplify l- guard $ getBracedModifier str == "[@]" && not ("!" `isPrefixOf` str)- return $ getBracedReference str-- -- This is much uglier than it should be- getArrayIfUsedAsIndex :: String -> Token -> Maybe (Token, String)- getArrayIfUsedAsIndex name t =- case t of- T_DollarBraced _ _ list -> do- let ref = getBracedReference $ concat $ oversimplify list- guard $ ref == name- -- We found a $name. Look up the chain to see if it's ${arr[$name]}- list@T_NormalWord {} <- Map.lookup (getId t) parents- (T_DollarBraced _ _ parentList) <- Map.lookup (getId list) parents- (T_Literal _ head : index : T_Literal _ tail : _) <- return $ getWordParts parentList- let str = concat $ oversimplify list- let modifier = getBracedModifier str- guard $ getId index == getId t- guard $ "[${VAR}]" `isPrefixOf` modifier- return (t, getBracedReference str)-- T_NormalWord wordId list -> do- -- We found just name. Check if it's part of ${something[name]}- parent@(T_DollarBraced _ _ parentList) <- Map.lookup wordId parents- let str = concat $ oversimplify t- let modifier = getBracedModifier str- guard $ ("[" ++ name ++ "]") `isPrefixOf` modifier- return (parent, getBracedReference str)-- TA_Variable indexId ref [] -> do- -- We found arithmetic name. See if it's part of arithmetic arr[name]- guard $ ref == name- (TA_Sequence seqId [element]) <- Map.lookup indexId parents- guard $ getId element == indexId- parent@(TA_Variable arrayId arrayName [element]) <- Map.lookup seqId parents- guard $ getId element == seqId- return (parent, arrayName)-- _ -> Nothing--prop_checkSetESuppressed1 = verifyTree checkSetESuppressed "set -e; f(){ :; }; x=$(f)"-prop_checkSetESuppressed2 = verifyNotTree checkSetESuppressed "f(){ :; }; x=$(f)"-prop_checkSetESuppressed3 = verifyNotTree checkSetESuppressed "set -e; f(){ :; }; x=$(set -e; f)"-prop_checkSetESuppressed4 = verifyTree checkSetESuppressed "set -e; f(){ :; }; baz=$(set -e; f) || :"-prop_checkSetESuppressed5 = verifyNotTree checkSetESuppressed "set -e; f(){ :; }; baz=$(echo \"\") || :"-prop_checkSetESuppressed6 = verifyTree checkSetESuppressed "set -e; f(){ :; }; f && echo"-prop_checkSetESuppressed7 = verifyTree checkSetESuppressed "set -e; f(){ :; }; f || echo"-prop_checkSetESuppressed8 = verifyNotTree checkSetESuppressed "set -e; f(){ :; }; echo && f"-prop_checkSetESuppressed9 = verifyNotTree checkSetESuppressed "set -e; f(){ :; }; echo || f"-prop_checkSetESuppressed10 = verifyTree checkSetESuppressed "set -e; f(){ :; }; ! f"-prop_checkSetESuppressed11 = verifyTree checkSetESuppressed "set -e; f(){ :; }; if f; then :; fi"-prop_checkSetESuppressed12 = verifyTree checkSetESuppressed "set -e; f(){ :; }; if set -e; f; then :; fi"-prop_checkSetESuppressed13 = verifyTree checkSetESuppressed "set -e; f(){ :; }; while f; do :; done"-prop_checkSetESuppressed14 = verifyTree checkSetESuppressed "set -e; f(){ :; }; while set -e; f; do :; done"-prop_checkSetESuppressed15 = verifyTree checkSetESuppressed "set -e; f(){ :; }; until f; do :; done"-prop_checkSetESuppressed16 = verifyTree checkSetESuppressed "set -e; f(){ :; }; until set -e; f; do :; done"-prop_checkSetESuppressed17 = verifyNotTree checkSetESuppressed "set -e; f(){ :; }; g(){ :; }; g f"-prop_checkSetESuppressed18 = verifyNotTree checkSetESuppressed "set -e; shopt -s inherit_errexit; f(){ :; }; x=$(f)"-prop_checkSetESuppressed19 = verifyNotTree checkSetESuppressed "set -e; set -o posix; f(){ :; }; x=$(f)"-checkSetESuppressed params t =- if hasSetE params then runNodeAnalysis checkNode params t else []- where- checkNode _ (T_SimpleCommand _ _ (cmd:_)) = when (isFunction cmd) (checkCmd cmd)- checkNode _ _ = return ()-- functions_ = functions t-- isFunction cmd = isJust $ do- literalArg <- getUnquotedLiteral cmd- Map.lookup literalArg functions_-- checkCmd cmd = go $ getPath (parentMap params) cmd- where- go (child:parent:rest) = do- case parent of- T_Banged _ condition | child `isIn` [condition] -> informConditional "a ! condition" cmd- T_AndIf _ condition _ | child `isIn` [condition] -> informConditional "an && condition" cmd- T_OrIf _ condition _ | child `isIn` [condition] -> informConditional "an || condition" cmd- T_IfExpression _ condition _ | child `isIn` concatMap fst condition -> informConditional "an 'if' condition" cmd- T_UntilExpression _ condition _ | child `isIn` condition -> informConditional "an 'until' condition" cmd- T_WhileExpression _ condition _ | child `isIn` condition -> informConditional "a 'while' condition" cmd- T_DollarExpansion {} | not $ errExitEnabled parent -> informUninherited cmd- T_Backticked {} | not $ errExitEnabled parent -> informUninherited cmd- _ -> return ()- go (parent:rest)- go _ = return ()-- informConditional condType t =- info (getId t) 2310 (- "This function is invoked in " ++ condType ++ " so set -e " ++- "will be disabled. Invoke separately if failures should " ++- "cause the script to exit.")- informUninherited t =- info (getId t) 2311 (- "Bash implicitly disabled set -e for this function " ++- "invocation because it's inside a command substitution. " ++- "Add set -e; before it or enable inherit_errexit.")- errExitEnabled t = hasInheritErrexit params || containsSetE t- isIn t cmds = getId t `elem` map getId cmds---prop_checkExtraMaskedReturns1 = verifyTree checkExtraMaskedReturns "cat < <(ls)"-prop_checkExtraMaskedReturns2 = verifyTree checkExtraMaskedReturns "read -ra arr <(ls)"-prop_checkExtraMaskedReturns3 = verifyTree checkExtraMaskedReturns "ls >(cat)"-prop_checkExtraMaskedReturns4 = verifyTree checkExtraMaskedReturns "false | true"-prop_checkExtraMaskedReturns5 = verifyNotTree checkExtraMaskedReturns "set -o pipefail; false | true"-prop_checkExtraMaskedReturns6 = verifyNotTree checkExtraMaskedReturns "false | true || true"-prop_checkExtraMaskedReturns7 = verifyTree checkExtraMaskedReturns "true $(false)"-prop_checkExtraMaskedReturns8 = verifyTree checkExtraMaskedReturns "x=$(false)$(true)"-prop_checkExtraMaskedReturns9 = verifyNotTree checkExtraMaskedReturns "x=$(false)true"-prop_checkExtraMaskedReturns10 = verifyTree checkExtraMaskedReturns "x=`false``false`"-prop_checkExtraMaskedReturns11 = verifyTree checkExtraMaskedReturns "x=\"$(false)$(true)\""-prop_checkExtraMaskedReturns12 = verifyTree checkExtraMaskedReturns "x=\"$(false)\"\"$(true)\""-prop_checkExtraMaskedReturns13 = verifyTree checkExtraMaskedReturns "true <<<$(false)"-prop_checkExtraMaskedReturns14 = verifyNotTree checkExtraMaskedReturns "echo asdf | false"-prop_checkExtraMaskedReturns15 = verifyNotTree checkExtraMaskedReturns "readonly x=$(false)"-prop_checkExtraMaskedReturns16 = verifyTree checkExtraMaskedReturns "readarray -t files < <(ls)"-prop_checkExtraMaskedReturns17 = verifyNotTree checkExtraMaskedReturns "x=( $(false) false )"-prop_checkExtraMaskedReturns18 = verifyTree checkExtraMaskedReturns "x=( $(false) $(false) )"-prop_checkExtraMaskedReturns19 = verifyNotTree checkExtraMaskedReturns "x=( $(false) [4]=false )"-prop_checkExtraMaskedReturns20 = verifyTree checkExtraMaskedReturns "x=( $(false) [4]=$(false) )"-prop_checkExtraMaskedReturns21 = verifyTree checkExtraMaskedReturns "cat << foo\n $(false)\nfoo"-prop_checkExtraMaskedReturns22 = verifyTree checkExtraMaskedReturns "[[ $(false) ]]"-prop_checkExtraMaskedReturns23 = verifyNotTree checkExtraMaskedReturns "x=$(false) y=z"-prop_checkExtraMaskedReturns24 = verifyNotTree checkExtraMaskedReturns "x=$(( $(date +%s) ))"-prop_checkExtraMaskedReturns25 = verifyTree checkExtraMaskedReturns "echo $(( $(date +%s) ))"-prop_checkExtraMaskedReturns26 = verifyNotTree checkExtraMaskedReturns "x=( $(false) )"-prop_checkExtraMaskedReturns27 = verifyTree checkExtraMaskedReturns "x=$(false) false"-prop_checkExtraMaskedReturns28 = verifyTree checkExtraMaskedReturns "x=$(false) y=$(false)"-prop_checkExtraMaskedReturns29 = verifyNotTree checkExtraMaskedReturns "false < <(set -e)"-prop_checkExtraMaskedReturns30 = verifyNotTree checkExtraMaskedReturns "false < <(shopt -s cdspell)"-prop_checkExtraMaskedReturns31 = verifyNotTree checkExtraMaskedReturns "false < <(dirname \"${BASH_SOURCE[0]}\")"-prop_checkExtraMaskedReturns32 = verifyNotTree checkExtraMaskedReturns "false < <(basename \"${BASH_SOURCE[0]}\")"-prop_checkExtraMaskedReturns33 = verifyNotTree checkExtraMaskedReturns "{ false || true; } | true"-prop_checkExtraMaskedReturns34 = verifyNotTree checkExtraMaskedReturns "{ false || :; } | true"-prop_checkExtraMaskedReturns35 = verifyTree checkExtraMaskedReturns "f() { local -r x=$(false); }"-prop_checkExtraMaskedReturns36 = verifyNotTree checkExtraMaskedReturns "time false"-prop_checkExtraMaskedReturns37 = verifyNotTree checkExtraMaskedReturns "time $(time false)"-prop_checkExtraMaskedReturns38 = verifyTree checkExtraMaskedReturns "x=$(time time time false) time $(time false)"--checkExtraMaskedReturns params t =- runNodeAnalysis findMaskingNodes params (removeTransparentCommands t)- where- findMaskingNodes _ (T_Arithmetic _ list) = findMaskedNodesInList [list]- findMaskingNodes _ (T_Array _ list) = findMaskedNodesInList $ allButLastSimpleCommands list- findMaskingNodes _ (T_Condition _ _ condition) = findMaskedNodesInList [condition]- findMaskingNodes _ (T_DoubleQuoted _ list) = findMaskedNodesInList $ allButLastSimpleCommands list- findMaskingNodes _ (T_HereDoc _ _ _ _ list) = findMaskedNodesInList list- findMaskingNodes _ (T_HereString _ word) = findMaskedNodesInList [word]- findMaskingNodes _ (T_NormalWord _ parts) = findMaskedNodesInList $ allButLastSimpleCommands parts- findMaskingNodes _ (T_Pipeline _ _ cmds) | not (hasPipefail params) = findMaskedNodesInList $ allButLastSimpleCommands cmds- findMaskingNodes _ (T_ProcSub _ _ list) = findMaskedNodesInList list- findMaskingNodes _ (T_SimpleCommand _ assigns (_:args)) = findMaskedNodesInList $ assigns ++ args- findMaskingNodes _ (T_SimpleCommand _ assigns []) = findMaskedNodesInList $ allButLastSimpleCommands assigns- findMaskingNodes _ _ = return ()-- findMaskedNodesInList = mapM_ (doAnalysis findMaskedNodes)-- isMaskedNode t = not (isHarmlessCommand t || isCheckedElsewhere t || isMaskDeliberate t)- findMaskedNodes t@(T_SimpleCommand _ _ (_:_)) = when (isMaskedNode t) $ inform t- findMaskedNodes t@T_Condition {} = when (isMaskedNode t) $ inform t- findMaskedNodes _ = return ()-- containsSimpleCommand t = isNothing $ doAnalysis go t- where- go t = case t of- T_SimpleCommand {} -> fail ""- _ -> return ()-- allButLastSimpleCommands cmds =- if null simpleCommands then [] else init simpleCommands- where- simpleCommands = filter containsSimpleCommand cmds-- removeTransparentCommands t =- doTransform go t- where- go cmd@(T_SimpleCommand id assigns (_:args)) | isTransparentCommand cmd- = T_SimpleCommand id assigns args- go t = t-- inform t = info (getId t) 2312 ("Consider invoking this command "- ++ "separately to avoid masking its return value (or use '|| true' "- ++ "to ignore).")-- isMaskDeliberate t = hasParent isOrIf t- where- isOrIf _ (T_OrIf _ _ (T_Pipeline _ _ [T_Redirecting _ _ cmd]))- = getCommandBasename cmd `elem` [Just "true", Just ":"]- isOrIf _ _ = False-- isCheckedElsewhere t = hasParent isDeclaringCommand t- where- isDeclaringCommand t _ = fromMaybe False $ do- cmd <- getCommand t- basename <- getCommandBasename cmd- return $- case basename of- -- local -r x=$(false) is intentionally ignored for SC2155- "local" | "r" `elem` (map snd $ getAllFlags cmd) -> False- _ -> basename `elem` declaringCommands-- isHarmlessCommand t = fromMaybe False $ do- basename <- getCommandBasename t- return $ basename `elem` [- "echo"- ,"basename"- ,"dirname"- ,"printf"- ,"set"- ,"shopt"- ]-- isTransparentCommand t = fromMaybe False $ do- basename <- getCommandBasename t- return $ basename == "time"-- parentChildPairs t = go $ parents params t- where- go (child:parent:rest) = (parent, child):go (parent:rest)- go _ = []-- hasParent pred t = any (uncurry pred) (parentChildPairs t)----- hard error on negated command that is not last-prop_checkBatsTestDoesNotUseNegation1 = verify checkBatsTestDoesNotUseNegation "#!/usr/bin/env/bats\n@test \"name\" { ! true; false; }"-prop_checkBatsTestDoesNotUseNegation2 = verify checkBatsTestDoesNotUseNegation "#!/usr/bin/env/bats\n@test \"name\" { ! [[ -e test ]]; false; }"-prop_checkBatsTestDoesNotUseNegation3 = verify checkBatsTestDoesNotUseNegation "#!/usr/bin/env/bats\n@test \"name\" { ! [ -e test ]; false; }"--- acceptable formats:--- using run-prop_checkBatsTestDoesNotUseNegation4 = verifyNot checkBatsTestDoesNotUseNegation "#!/usr/bin/env/bats\n@test \"name\" { run ! true; }"--- using || false-prop_checkBatsTestDoesNotUseNegation5 = verifyNot checkBatsTestDoesNotUseNegation "#!/usr/bin/env/bats\n@test \"name\" { ! [[ -e test ]] || false; }"-prop_checkBatsTestDoesNotUseNegation6 = verifyNot checkBatsTestDoesNotUseNegation "#!/usr/bin/env/bats\n@test \"name\" { ! [ -e test ] || false; }"--- only style warning when last command-prop_checkBatsTestDoesNotUseNegation7 = verifyCodes checkBatsTestDoesNotUseNegation [2314] "#!/usr/bin/env/bats\n@test \"name\" { ! true; }"-prop_checkBatsTestDoesNotUseNegation8 = verifyCodes checkBatsTestDoesNotUseNegation [2315] "#!/usr/bin/env/bats\n@test \"name\" { ! [[ -e test ]]; }"-prop_checkBatsTestDoesNotUseNegation9 = verifyCodes checkBatsTestDoesNotUseNegation [2315] "#!/usr/bin/env/bats\n@test \"name\" { ! [ -e test ]; }"--checkBatsTestDoesNotUseNegation params t =- case t of- T_BatsTest _ _ (T_BraceGroup _ commands) -> mapM_ (check commands) commands- _ -> return ()- where- check commands t =- case t of- T_Banged id (T_Pipeline _ _ [T_Redirecting _ _ (T_Condition idCondition _ _)]) ->- if t `isLastOf` commands- then style id 2315 "In Bats, ! will not fail the test if it is not the last command anymore. Fold the `!` into the conditional!"- else err id 2315 "In Bats, ! does not cause a test failure. Fold the `!` into the conditional!"-- T_Banged id cmd -> if t `isLastOf` commands- then styleWithFix id 2314 "In Bats, ! will not fail the test if it is not the last command anymore. Use `run ! ` (on Bats >= 1.5.0) instead."- (fixWith [replaceStart id params 0 "run "])- else errWithFix id 2314 "In Bats, ! does not cause a test failure. Use 'run ! ' (on Bats >= 1.5.0) instead."- (fixWith [replaceStart id params 0 "run "])- _ -> return ()- isLastOf t commands =- case commands of- [x] -> x == t- x:rest -> isLastOf t rest- [] -> False---prop_checkCommandIsUnreachable1 = verify checkCommandIsUnreachable "foo; bar; exit; baz"-prop_checkCommandIsUnreachable2 = verify checkCommandIsUnreachable "die() { exit; }; foo; bar; die; baz"-prop_checkCommandIsUnreachable3 = verifyNot checkCommandIsUnreachable "foo; bar || exit; baz"-checkCommandIsUnreachable params t =- case t of- T_Pipeline {} -> sequence_ $ do- state <- CF.getIncomingState (cfgAnalysis params) id- guard . not $ CF.stateIsReachable state- guard . not $ isSourced params t- return $ info id 2317 "Command appears to be unreachable. Check usage (or ignore if invoked indirectly)."- _ -> return ()- where id = getId t---prop_checkOverwrittenExitCode1 = verify checkOverwrittenExitCode "x; [ $? -eq 1 ] || [ $? -eq 2 ]"-prop_checkOverwrittenExitCode2 = verifyNot checkOverwrittenExitCode "x; [ $? -eq 1 ]"-prop_checkOverwrittenExitCode3 = verify checkOverwrittenExitCode "x; echo \"Exit is $?\"; [ $? -eq 0 ]"-prop_checkOverwrittenExitCode4 = verifyNot checkOverwrittenExitCode "x; [ $? -eq 0 ] && echo Success"-prop_checkOverwrittenExitCode5 = verify checkOverwrittenExitCode "x; if [ $? -eq 0 ]; then var=$?; fi"-prop_checkOverwrittenExitCode6 = verify checkOverwrittenExitCode "x; [ $? -gt 0 ] && fail=$?"-prop_checkOverwrittenExitCode7 = verifyNot checkOverwrittenExitCode "[ 1 -eq 2 ]; status=$?"-prop_checkOverwrittenExitCode8 = verifyNot checkOverwrittenExitCode "[ 1 -eq 2 ]; exit $?"-checkOverwrittenExitCode params t =- case t of- T_DollarBraced id _ val | getLiteralString val == Just "?" -> check id- _ -> return ()- where- check id = sequence_ $ do- state <- CF.getIncomingState (cfgAnalysis params) id- let exitCodeIds = CF.exitCodes state- guard . not $ S.null exitCodeIds-- let idToToken = idMap params- exitCodeTokens <- sequence $ map (\k -> Map.lookup k idToToken) $ S.toList exitCodeIds- return $ do- when (all isCondition exitCodeTokens && not (usedUnconditionally t exitCodeIds)) $- warn id 2319 "This $? refers to a condition, not a command. Assign to a variable to avoid it being overwritten."- when (all isPrinting exitCodeTokens) $- warn id 2320 "This $? refers to echo/printf, not a previous command. Assign to variable to avoid it being overwritten."-- isCondition t =- case t of- T_Condition {} -> True- T_SimpleCommand {} -> getCommandName t == Just "test"- _ -> False-- -- If we don't do anything based on the condition, assume we wanted the condition itself- -- This helps differentiate `x; [ $? -gt 0 ] && exit $?` vs `[ cond ]; exit $?`- usedUnconditionally t testIds =- all (\c -> CF.doesPostDominate (cfgAnalysis params) (getId t) c) testIds-- isPrinting t =- case getCommandBasename t of- Just "echo" -> True- Just "printf" -> True- _ -> False---prop_checkUnnecessaryArithmeticExpansionIndex1 = verify checkUnnecessaryArithmeticExpansionIndex "a[$((1+1))]=n"-prop_checkUnnecessaryArithmeticExpansionIndex2 = verifyNot checkUnnecessaryArithmeticExpansionIndex "a[1+1]=n"-prop_checkUnnecessaryArithmeticExpansionIndex3 = verifyNot checkUnnecessaryArithmeticExpansionIndex "a[$(echo $((1+1)))]=n"-prop_checkUnnecessaryArithmeticExpansionIndex4 = verifyNot checkUnnecessaryArithmeticExpansionIndex "declare -A a; a[$((1+1))]=val"-checkUnnecessaryArithmeticExpansionIndex params t =- case t of- T_Assignment _ mode var [TA_Sequence _ [ TA_Expansion _ [expansion@(T_DollarArithmetic id _)]]] val ->- styleWithFix id 2321 "Array indices are already arithmetic contexts. Prefer removing the $(( and ))." $ fix id- _ -> return ()-- where- fix id =- fixWith [- replaceStart id params 3 "", -- Remove "$(("- replaceEnd id params 2 "" -- Remove "))"- ]---prop_checkUnnecessaryParens1 = verify checkUnnecessaryParens "echo $(( ((1+1)) ))"-prop_checkUnnecessaryParens2 = verify checkUnnecessaryParens "x[((1+1))+1]=1"-prop_checkUnnecessaryParens3 = verify checkUnnecessaryParens "x[(1+1)]=1"-prop_checkUnnecessaryParens4 = verify checkUnnecessaryParens "$(( (x) ))"-prop_checkUnnecessaryParens5 = verify checkUnnecessaryParens "(( (x) ))"-prop_checkUnnecessaryParens6 = verifyNot checkUnnecessaryParens "x[(1+1)+1]=1"-prop_checkUnnecessaryParens7 = verifyNot checkUnnecessaryParens "(( (1*1)+1 ))"-prop_checkUnnecessaryParens8 = verifyNot checkUnnecessaryParens "(( (1)+1 ))"-checkUnnecessaryParens params t =- case t of- T_DollarArithmetic _ t -> checkLeading "$(( (x) )) is the same as $(( x ))" t- T_ForArithmetic _ x y z _ -> mapM_ (checkLeading "for (((x); (y); (z))) is the same as for ((x; y; z))") [x,y,z]- T_Assignment _ _ _ [t] _ -> checkLeading "a[(x)] is the same as a[x]" t- T_Arithmetic _ t -> checkLeading "(( (x) )) is the same as (( x ))" t- TA_Parentesis _ (TA_Sequence _ [ TA_Parentesis id _ ]) ->- styleWithFix id 2322 "In arithmetic contexts, ((x)) is the same as (x). Prefer only one layer of parentheses." $ fix id- _ -> return ()- where-- checkLeading str t =- case t of- TA_Sequence _ [TA_Parentesis id _ ] -> styleWithFix id 2323 (str ++ ". Prefer not wrapping in additional parentheses.") $ fix id- _ -> return ()-- fix id =- fixWith [- replaceStart id params 1 "", -- Remove "("- replaceEnd id params 1 "" -- Remove ")"- ]-+ Copyright 2012-2024 Vidar Holen++ This file is part of ShellCheck.+ https://www.shellcheck.net++ ShellCheck is free software: you can redistribute it and/or modify+ it under the terms of the GNU General Public License as published by+ the Free Software Foundation, either version 3 of the License, or+ (at your option) any later version.++ ShellCheck is distributed in the hope that it will be useful,+ but WITHOUT ANY WARRANTY; without even the implied warranty of+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ GNU General Public License for more details.++ You should have received a copy of the GNU General Public License+ along with this program. If not, see <https://www.gnu.org/licenses/>.+-}+{-# LANGUAGE TemplateHaskell #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE PatternGuards #-}+{-# LANGUAGE NondecreasingIndentation #-}+module ShellCheck.Analytics (checker, optionalChecks, ShellCheck.Analytics.runTests) where++import ShellCheck.AST+import ShellCheck.ASTLib+import ShellCheck.AnalyzerLib hiding (producesComments)+import ShellCheck.CFG+import qualified ShellCheck.CFGAnalysis as CF+import ShellCheck.Data+import ShellCheck.Fixer (applyFix)+import ShellCheck.Parser+import ShellCheck.Prelude+import ShellCheck.Interface+import ShellCheck.Regex++import Control.Arrow (first)+import Control.Monad+import Control.Monad.Identity+import Control.Monad.State+import Control.Monad.Writer hiding ((<>))+import Control.Monad.Reader+import Data.Array (listArray)+import Data.Char+import Data.Functor+import Data.Function (on)+import Data.List+import Data.Maybe+import Data.Ord+import Data.Semigroup+import Debug.Trace -- STRIP+import qualified Data.List.NonEmpty as NE+import qualified Data.Map.Strict as Map+import qualified Data.Set as S+import Test.QuickCheck.All (forAllProperties)+import Test.QuickCheck.Test (quickCheckWithResult, stdArgs, maxSuccess)++-- Checks that are run on the AST root+treeChecks :: [Parameters -> Token -> [TokenComment]]+treeChecks = [+ nodeChecksToTreeCheck nodeChecks+ ,subshellAssignmentCheck+ ,checkQuotesInLiterals+ ,checkShebangParameters+ ,checkFunctionsUsedExternally+ ,checkUnusedAssignments+ ,checkUnpassedInFunctions+ ,checkArrayWithoutIndex+ ,checkShebang+ ,checkUnassignedReferences+ ,checkUncheckedCdPushdPopd+ ,checkArrayAssignmentIndices+ ,checkUseBeforeDefinition+ ,checkAliasUsedInSameParsingUnit+ ,checkArrayValueUsedAsIndex+ ]++checker spec params = mkChecker spec params treeChecks++mkChecker spec params checks =+ Checker {+ perScript = \(Root root) -> do+ tell $ concatMap (\f -> f params root) all,+ perToken = const $ return ()+ }+ where+ all = checks ++ optionals+ optionalKeys = asOptionalChecks spec+ optionals =+ if "all" `elem` optionalKeys+ then map snd optionalTreeChecks+ else mapMaybe (\c -> Map.lookup c optionalCheckMap) optionalKeys+++checkList l t = concatMap (\f -> f t) l++-- Checks that are run on each node in the AST+runNodeAnalysis f p t = execWriter (doAnalysis (f p) t)++-- Perform multiple node checks in a single iteration over the tree+nodeChecksToTreeCheck checkList =+ runNodeAnalysis+ (\p t -> (mapM_ ((\ f -> f t) . (\ f -> f p))+ checkList))++nodeChecks :: [Parameters -> Token -> Writer [TokenComment] ()]+nodeChecks = [+ checkPipePitfalls+ ,checkForInQuoted+ ,checkForInLs+ ,checkShorthandIf+ ,checkDollarStar+ ,checkUnquotedDollarAt+ ,checkStderrRedirect+ ,checkUnquotedN+ ,checkNumberComparisons+ ,checkSingleBracketOperators+ ,checkDoubleBracketOperators+ ,checkLiteralBreakingTest+ ,checkConstantNullary+ ,checkDivBeforeMult+ ,checkArithmeticDeref+ ,checkArithmeticBadOctal+ ,checkComparisonAgainstGlob+ ,checkCaseAgainstGlob+ ,checkCommarrays+ ,checkOrNeq+ ,checkAndEq+ ,checkEchoWc+ ,checkConstantIfs+ ,checkPipedAssignment+ ,checkAssignAteCommand+ ,checkUuoeVar+ ,checkQuotedCondRegex+ ,checkForInCat+ ,checkFindExec+ ,checkValidCondOps+ ,checkGlobbedRegex+ ,checkTestRedirects+ ,checkBadParameterSubstitution+ ,checkPS1Assignments+ ,checkBackticks+ ,checkInexplicablyUnquoted+ ,checkTildeInQuotes+ ,checkLonelyDotDash+ ,checkSpuriousExec+ ,checkSpuriousExpansion+ ,checkDollarBrackets+ ,checkSshHereDoc+ ,checkGlobsAsOptions+ ,checkWhileReadPitfalls+ ,checkArithmeticOpCommand+ ,checkCharRangeGlob+ ,checkUnquotedExpansions+ ,checkSingleQuotedVariables+ ,checkRedirectToSame+ ,checkPrefixAssignmentReference+ ,checkLoopKeywordScope+ ,checkCdAndBack+ ,checkWrongArithmeticAssignment+ ,checkConditionalAndOrs+ ,checkFunctionDeclarations+ ,checkOverridingPath+ ,checkArrayAsString+ ,checkUnsupported+ ,checkMultipleAppends+ ,checkSuspiciousIFS+ ,checkShouldUseGrepQ+ ,checkTestArgumentSplitting+ ,checkConcatenatedDollarAt+ ,checkTildeInPath+ ,checkReadWithoutR+ ,checkCpLegacyR+ ,checkLoopVariableReassignment+ ,checkTrailingBracket+ ,checkReturnAgainstZero+ ,checkRedirectedNowhere+ ,checkUnmatchableCases+ ,checkSubshellAsTest+ ,checkSplittingInArrays+ ,checkRedirectionToNumber+ ,checkGlobAsCommand+ ,checkFlagAsCommand+ ,checkEmptyCondition+ ,checkPipeToNowhere+ ,checkForLoopGlobVariables+ ,checkSubshelledTests+ ,checkRedirectionToCommand+ ,checkDollarQuoteParen+ ,checkUselessBang+ ,checkTranslatedStringVariable+ ,checkModifiedArithmeticInRedirection+ ,checkBlatantRecursion+ ,checkBadTestAndOr+ ,checkAssignToSelf+ ,checkEqualsInCommand+ ,checkSecondArgIsComparison+ ,checkComparisonWithLeadingX+ ,checkCommandWithTrailingSymbol+ ,checkUnquotedParameterExpansionPattern+ ,checkBatsTestDoesNotUseNegation+ ,checkCommandIsUnreachable+ ,checkSpacefulnessCfg+ ,checkOverwrittenExitCode+ ,checkUnnecessaryArithmeticExpansionIndex+ ,checkUnnecessaryParens+ ,checkPlusEqualsNumber+ ,checkExpansionWithRedirection+ ,checkUnaryTestA+ ]++optionalChecks = map fst optionalTreeChecks+++prop_verifyOptionalExamples = all check optionalTreeChecks+ where+ check (desc, check) =+ verifyCodesTree check (cdId desc) (cdPositive desc)+ && verifyNotTree check (cdNegative desc)+++optionalTreeChecks :: [(CheckDescription, (Parameters -> Token -> [TokenComment]))]+optionalTreeChecks = [+ (newCheckDescription {+ cdName = "quote-safe-variables",+ cdId = [2248],+ cdDescription = "Suggest quoting variables without metacharacters",+ cdPositive = "var=hello; echo $var",+ cdNegative = "var=hello; echo \"$var\""+ }, nodeChecksToTreeCheck [checkVerboseSpacefulnessCfg])++ ,(newCheckDescription {+ cdName = "avoid-nullary-conditions",+ cdId = [2243, 2244],+ cdDescription = "Suggest explicitly using -n in `[ $var ]`",+ cdPositive = "[ \"$var\" ] && [ \"$(cmd)\" ]",+ cdNegative = "[ -n \"$var\" ] && [ -n \"$(cmd)\" ]"+ }, nodeChecksToTreeCheck [checkNullaryExpansionTest])++ ,(newCheckDescription {+ cdName = "avoid-negated-conditions",+ cdId = [2335],+ cdDescription = "Suggest removing unnecessary comparison negations",+ cdPositive = "[ ! \"$var\" -eq 1 ]",+ cdNegative = "[ \"$var\" -ne 1 ]"+ }, nodeChecksToTreeCheck [checkUnnecessarilyInvertedTest])++ ,(newCheckDescription {+ cdName = "add-default-case",+ cdId = [2249],+ cdDescription = "Suggest adding a default case in `case` statements",+ cdPositive = "case $? in 0) echo 'Success';; esac",+ cdNegative = "case $? in 0) echo 'Success';; *) echo 'Fail' ;; esac"+ }, nodeChecksToTreeCheck [checkDefaultCase])++ ,(newCheckDescription {+ cdName = "require-variable-braces",+ cdId = [2250],+ cdDescription = "Suggest putting braces around all variable references",+ cdPositive = "var=hello; echo $var",+ cdNegative = "var=hello; echo ${var}"+ }, nodeChecksToTreeCheck [checkVariableBraces])++ ,(newCheckDescription {+ cdName = "check-unassigned-uppercase",+ cdId = [2154],+ cdDescription = "Warn when uppercase variables are unassigned",+ cdPositive = "echo $VAR",+ cdNegative = "VAR=hello; echo $VAR"+ }, checkUnassignedReferences' True)++ ,(newCheckDescription {+ cdName = "require-double-brackets",+ cdId = [2292],+ cdDescription = "Require [[ and warn about [ in Bash/Ksh",+ cdPositive = "[ -e /etc/issue ]",+ cdNegative = "[[ -e /etc/issue ]]"+ }, checkRequireDoubleBracket)++ ,(newCheckDescription {+ cdName = "require-double-equals",+ cdId = [2338],+ cdDescription = "Require == and warn about = in Bash tests",+ cdPositive = "[[ \"$x\" = \"$y\" ]]",+ cdNegative = "[[ \"$x\" == \"$y\" ]]"+ }, checkRequireDoubleEquals)++ ,(newCheckDescription {+ cdName = "check-set-e-suppressed",+ cdId = [2310, 2311],+ cdDescription = "Notify when set -e is suppressed during function invocation",+ cdPositive = "set -e; func() { cp *.txt ~/backup; rm *.txt; }; func && echo ok; x=$(func)",+ cdNegative = "set -e; func() { cp *.txt ~/backup; rm *.txt; }; func; echo ok; x=$(set -e; func)"+ }, checkSetESuppressed)++ ,(newCheckDescription {+ cdName = "check-extra-masked-returns",+ cdId = [2312],+ cdDescription = "Check for additional cases where exit codes are masked",+ cdPositive = "rm -r \"$(get_chroot_dir)/home\"",+ cdNegative = "set -e; dir=\"$(get_chroot_dir)\"; rm -r \"$dir/home\""+ }, checkExtraMaskedReturns)++ ,(newCheckDescription {+ cdName = "useless-use-of-cat",+ cdId = [2002],+ cdDescription = "Check for Useless Use Of Cat (UUOC)",+ cdPositive = "cat foo | grep bar",+ cdNegative = "grep bar foo"+ }, nodeChecksToTreeCheck [checkUuoc])+ ]++optionalCheckMap :: Map.Map String (Parameters -> Token -> [TokenComment])+optionalCheckMap = Map.fromList $ map item optionalTreeChecks+ where+ item (desc, check) = (cdName desc, check)++wouldHaveBeenGlob s = '*' `elem` s++verify :: (Parameters -> Token -> Writer [TokenComment] ()) -> String -> Bool+verify f s = checkNode f s == Just True++verifyNot :: (Parameters -> Token -> Writer [TokenComment] ()) -> String -> Bool+verifyNot f s = checkNode f s == Just False++verifyTree :: (Parameters -> Token -> [TokenComment]) -> String -> Bool+verifyTree f s = producesComments f s == Just True++verifyNotTree :: (Parameters -> Token -> [TokenComment]) -> String -> Bool+verifyNotTree f s = producesComments f s == Just False++-- Verify that applying all suggested fixes to the script gives the expected result+verifyTreeFix :: (Parameters -> Token -> [TokenComment]) -> String -> String -> Bool+verifyTreeFix f s expected = fixed == Just (lines expected)+ where+ fixed = do+ comments <- runAndGetComments f s+ let combinedFix = mconcat $ mapMaybe tcFix comments+ let scriptLines = lines s+ return $ applyFix combinedFix (listArray (1, length scriptLines) scriptLines)++checkCommand str f t@(T_SimpleCommand id _ (cmd:rest))+ | t `isCommand` str = f cmd rest+checkCommand _ _ _ = return ()++checkUnqualifiedCommand str f t@(T_SimpleCommand id _ (cmd:rest))+ | t `isUnqualifiedCommand` str = f cmd rest+checkUnqualifiedCommand _ _ _ = return ()++verifyCodes :: (Parameters -> Token -> Writer [TokenComment] ()) -> [Code] -> String -> Bool+verifyCodes f = verifyCodesTree (runNodeAnalysis f)++verifyCodesTree :: (Parameters -> Token -> [TokenComment]) -> [Code] -> String -> Bool+verifyCodesTree treeCheck l s =+ fmap sort codes == Just (sort l)+ where+ comments = runAndGetComments treeCheck s+ codes = map (cCode . tcComment) <$> comments++checkNode f = producesComments (runNodeAnalysis f)+producesComments :: (Parameters -> Token -> [TokenComment]) -> String -> Maybe Bool+producesComments f s = not . null <$> runAndGetComments f s++runAndGetComments f s = do+ let pr = pScript s+ root <- prRoot pr+ let spec = defaultSpec pr+ let params = makeParameters spec+ return $+ filterByAnnotation spec params $+ f params root++-- Copied from https://wiki.haskell.org/Edit_distance+dist :: Eq a => [a] -> [a] -> Int+dist a b+ = last (if lab == 0 then mainDiag+ else if lab > 0 then lowers !! (lab - 1)+ else{- < 0 -} uppers !! (-1 - lab))+ where mainDiag = oneDiag a b (head uppers) (-1 : head lowers)+ uppers = eachDiag a b (mainDiag : uppers) -- upper diagonals+ lowers = eachDiag b a (mainDiag : lowers) -- lower diagonals+ eachDiag a [] diags = []+ eachDiag a (bch:bs) (lastDiag:diags) = oneDiag a bs nextDiag lastDiag : eachDiag a bs diags+ where nextDiag = head (drop 1 diags)+ oneDiag a b diagAbove diagBelow = thisdiag+ where doDiag [] b nw n w = []+ doDiag a [] nw n w = []+ doDiag (ach:as) (bch:bs) nw n w = me : doDiag as bs me (drop 1 n) (drop 1 w)+ where me = if ach == bch then nw else 1 + min3 (head w) nw (head n)+ firstelt = 1 + head diagBelow+ thisdiag = firstelt : doDiag a b firstelt diagAbove (drop 1 diagBelow)+ lab = length a - length b+ min3 x y z = if x < y then x else min y z++hasFloatingPoint params = shellType params == Ksh++-- helpers to build replacements+replaceStart id params n r =+ let tp = tokenPositions params+ (start, _) = tp Map.! id+ new_end = start {+ posColumn = posColumn start + n+ }+ depth = length $ getPath (parentMap params) (T_EOF id)+ in+ newReplacement {+ repStartPos = start,+ repEndPos = new_end,+ repString = r,+ repPrecedence = depth,+ repInsertionPoint = InsertAfter+ }+replaceEnd id params n r =+ let tp = tokenPositions params+ (_, end) = tp Map.! id+ new_start = end {+ posColumn = posColumn end - n+ }+ new_end = end {+ posColumn = posColumn end+ }+ depth = length $ getPath (parentMap params) (T_EOF id)+ in+ newReplacement {+ repStartPos = new_start,+ repEndPos = new_end,+ repString = r,+ repPrecedence = depth,+ repInsertionPoint = InsertBefore+ }+replaceToken id params r =+ let tp = tokenPositions params+ (start, end) = tp Map.! id+ depth = length $ getPath (parentMap params) (T_EOF id)+ in+ newReplacement {+ repStartPos = start,+ repEndPos = end,+ repString = r,+ repPrecedence = depth,+ repInsertionPoint = InsertBefore+ }++surroundWith id params s = fixWith [replaceStart id params 0 s, replaceEnd id params 0 s]+fixWith fixes = newFix { fixReplacements = fixes }++analyse f t = execState (doAnalysis f t) []++-- Make a map from functions to definition IDs+functions t = Map.fromList $ analyse findFunctions t+findFunctions (T_Function id _ _ name _)+ = modify ((name, id):)+findFunctions _ = return ()++-- Make a map from aliases to definition IDs+aliases t = Map.fromList $ analyse findAliases t+findAliases t@(T_SimpleCommand _ _ (_:args))+ | t `isUnqualifiedCommand` "alias" = mapM_ getAlias args+findAliases _ = return ()+getAlias arg =+ let string = onlyLiteralString arg+ in when ('=' `elem` string) $+ modify ((takeWhile (/= '=') string, getId arg):)++prop_checkEchoWc3 = verify checkEchoWc "n=$(echo $foo | wc -c)"+checkEchoWc _ (T_Pipeline id _ [a, b]) =+ when (acmd == ["echo", "${VAR}"]) $+ case bcmd of+ ["wc", "-c"] -> countMsg+ ["wc", "-m"] -> countMsg+ _ -> return ()+ where+ acmd = oversimplify a+ bcmd = oversimplify b+ countMsg = style id 2000 "See if you can use ${#variable} instead."+checkEchoWc _ _ = return ()++prop_checkPipedAssignment1 = verify checkPipedAssignment "A=ls | grep foo"+prop_checkPipedAssignment2 = verifyNot checkPipedAssignment "A=foo cmd | grep foo"+prop_checkPipedAssignment3 = verifyNot checkPipedAssignment "A=foo"+checkPipedAssignment _ (T_Pipeline _ _ (T_Redirecting _ _ (T_SimpleCommand id (_:_) []):_:_)) =+ warn id 2036 "If you wanted to assign the output of the pipeline, use a=$(b | c) ."+checkPipedAssignment _ _ = return ()++prop_checkAssignAteCommand1 = verify checkAssignAteCommand "A=ls -l"+prop_checkAssignAteCommand2 = verify checkAssignAteCommand "A=ls --sort=$foo"+prop_checkAssignAteCommand3 = verify checkAssignAteCommand "A=cat foo | grep bar"+prop_checkAssignAteCommand4 = verifyNot checkAssignAteCommand "A=foo ls -l"+prop_checkAssignAteCommand5 = verify checkAssignAteCommand "PAGER=cat grep bar"+prop_checkAssignAteCommand6 = verifyNot checkAssignAteCommand "PAGER=\"cat\" grep bar"+prop_checkAssignAteCommand7 = verify checkAssignAteCommand "here=pwd"+checkAssignAteCommand _ (T_SimpleCommand id [T_Assignment _ _ _ _ assignmentTerm] list) =+ -- Check if first word is intended as an argument (flag or glob).+ if firstWordIsArg list+ then+ err id 2037 "To assign the output of a command, use var=$(cmd) ."+ else+ -- Check if it's a known, unquoted command name.+ when (isCommonCommand $ getUnquotedLiteral assignmentTerm) $+ warn id 2209 "Use var=$(command) to assign output (or quote to assign string)."+ where+ isCommonCommand (Just s) = s `elem` commonCommands+ isCommonCommand _ = False+ firstWordIsArg (head:_) = isGlob head || isUnquotedFlag head+ firstWordIsArg [] = False++checkAssignAteCommand _ _ = return ()++prop_checkArithmeticOpCommand1 = verify checkArithmeticOpCommand "i=i + 1"+prop_checkArithmeticOpCommand2 = verify checkArithmeticOpCommand "foo=bar * 2"+prop_checkArithmeticOpCommand3 = verifyNot checkArithmeticOpCommand "foo + opts"+checkArithmeticOpCommand _ (T_SimpleCommand id [T_Assignment {}] (firstWord:_)) =+ mapM_ check $ getGlobOrLiteralString firstWord+ where+ check op =+ when (op `elem` ["+", "-", "*", "/"]) $+ warn (getId firstWord) 2099 $+ "Use $((..)) for arithmetics, e.g. i=$((i " ++ op ++ " 2))"+checkArithmeticOpCommand _ _ = return ()++prop_checkWrongArit = verify checkWrongArithmeticAssignment "i=i+1"+prop_checkWrongArit2 = verify checkWrongArithmeticAssignment "n=2; i=n*2"+checkWrongArithmeticAssignment params (T_SimpleCommand id [T_Assignment _ _ _ _ val] []) =+ sequence_ $ do+ str <- getNormalString val+ var:op:_ <- matchRegex regex str+ guard $ S.member var references+ return . warn (getId val) 2100 $+ "Use $((..)) for arithmetics, e.g. i=$((i " ++ op ++ " 2))"+ where+ regex = mkRegex "^([_a-zA-Z][_a-zA-Z0-9]*)([+*-]).+$"+ references = S.fromList [name | Assignment (_, _, name, _) <- variableFlow params]++ getNormalString (T_NormalWord _ words) = do+ parts <- mapM getLiterals words+ return $ concat parts+ getNormalString _ = Nothing++ getLiterals (T_Literal _ s) = return s+ getLiterals (T_Glob _ s) = return s+ getLiterals _ = Nothing+checkWrongArithmeticAssignment _ _ = return ()+++prop_checkUuoc1 = verify checkUuoc "cat foo | grep bar"+prop_checkUuoc2 = verifyNot checkUuoc "cat * | grep bar"+prop_checkUuoc3 = verify checkUuoc "cat \"$var\" | grep bar"+prop_checkUuoc3b = verifyNot checkUuoc "cat $var | grep bar"+prop_checkUuoc3c = verifyNot checkUuoc "cat \"${!var}\" | grep bar"+prop_checkUuoc4 = verifyNot checkUuoc "cat $var"+prop_checkUuoc5 = verifyNot checkUuoc "cat \"$@\""+prop_checkUuoc6 = verifyNot checkUuoc "cat -n | grep bar"+checkUuoc _ (T_Pipeline _ _ (T_Redirecting _ _ cmd:_:_)) =+ checkCommand "cat" (const f) cmd+ where+ f [word] | not (mayBecomeMultipleArgs word || isOption word) =+ style (getId word) 2002 "Useless cat. Consider 'cmd < file | ..' or 'cmd file | ..' instead."+ f _ = return ()+ isOption word = "-" `isPrefixOf` onlyLiteralString word+checkUuoc _ _ = return ()++prop_checkPipePitfalls3 = verify checkPipePitfalls "ls | grep -v mp3"+prop_checkPipePitfalls4 = verifyNot checkPipePitfalls "find . -print0 | xargs -0 foo"+prop_checkPipePitfalls5 = verifyNot checkPipePitfalls "ls -N | foo"+prop_checkPipePitfalls6 = verify checkPipePitfalls "find . | xargs foo"+prop_checkPipePitfalls7 = verifyNot checkPipePitfalls "find . -printf '%s\\n' | xargs foo"+prop_checkPipePitfalls8 = verify checkPipePitfalls "foo | grep bar | wc -l"+prop_checkPipePitfalls9 = verifyNot checkPipePitfalls "foo | grep -o bar | wc -l"+prop_checkPipePitfalls10 = verifyNot checkPipePitfalls "foo | grep -o bar | wc"+prop_checkPipePitfalls11 = verifyNot checkPipePitfalls "foo | grep bar | wc"+prop_checkPipePitfalls12 = verifyNot checkPipePitfalls "foo | grep -o bar | wc -c"+prop_checkPipePitfalls13 = verifyNot checkPipePitfalls "foo | grep bar | wc -c"+prop_checkPipePitfalls14 = verifyNot checkPipePitfalls "foo | grep -o bar | wc -cmwL"+prop_checkPipePitfalls15 = verifyNot checkPipePitfalls "foo | grep bar | wc -cmwL"+prop_checkPipePitfalls16 = verifyNot checkPipePitfalls "foo | grep -r bar | wc -l"+prop_checkPipePitfalls17 = verifyNot checkPipePitfalls "foo | grep -l bar | wc -l"+prop_checkPipePitfalls18 = verifyNot checkPipePitfalls "foo | grep -L bar | wc -l"+prop_checkPipePitfalls19 = verifyNot checkPipePitfalls "foo | grep -A2 bar | wc -l"+prop_checkPipePitfalls20 = verifyNot checkPipePitfalls "foo | grep -B999 bar | wc -l"+prop_checkPipePitfalls21 = verifyNot checkPipePitfalls "foo | grep --after-context 999 bar | wc -l"+prop_checkPipePitfalls22 = verifyNot checkPipePitfalls "foo | grep -B 1 --after-context 999 bar | wc -l"+prop_checkPipePitfalls23 = verifyNot checkPipePitfalls "ps -o pid,args -p $(pgrep java) | grep -F net.shellcheck.Test"+checkPipePitfalls _ (T_Pipeline id _ commands) = do+ for ["find", "xargs"] $+ \(find:xargs:_) ->+ let args = oversimplify xargs ++ oversimplify find+ in+ unless (any ($ args) [+ hasShortParameter '0',+ hasParameter "null",+ hasParameter "print0",+ hasParameter "printf"+ ]) $ warn (getId find) 2038+ "Use 'find .. -print0 | xargs -0 ..' or 'find .. -exec .. +' to allow non-alphanumeric filenames."++ for ["ps", "grep"] $+ \(ps:grep:_) ->+ let+ psFlags = maybe [] (map snd . getAllFlags) $ getCommand ps+ in+ -- There are many ways to specify a pid: 1, -1, p 1, wup 1, -q 1, -p 1, --pid 1.+ -- For simplicity we only deal with the most canonical looking flags:+ unless (any (`elem` ["p", "pid", "q", "quick-pid"]) psFlags) $+ info (getId ps) 2009 "Consider using pgrep instead of grepping ps output."++ for ["grep", "wc"] $+ \(grep:wc:_) ->+ let flagsGrep = maybe [] (map snd . getAllFlags) $ getCommand grep+ flagsWc = maybe [] (map snd . getAllFlags) $ getCommand wc+ in+ unless (any (`elem` ["l", "files-with-matches", "L", "files-without-matches", "o", "only-matching", "r", "R", "recursive", "A", "after-context", "B", "before-context"]) flagsGrep+ || any (`elem` ["m", "chars", "w", "words", "c", "bytes", "L", "max-line-length"]) flagsWc+ || null flagsWc) $+ style (getId grep) 2126 "Consider using 'grep -c' instead of 'grep|wc -l'."++ didLs <- fmap or . sequence $ [+ for' ["ls", "grep"] $+ \x -> warn x 2010 "Don't use ls | grep. Use a glob or a for loop with a condition to allow non-alphanumeric filenames.",+ for' ["ls", "xargs"] $+ \x -> warn x 2011 "Use 'find .. -print0 | xargs -0 ..' or 'find .. -exec .. +' to allow non-alphanumeric filenames."+ ]+ unless didLs $ void $+ for ["ls", "?"] $+ \(ls:_) -> unless (hasShortParameter 'N' (oversimplify ls)) $+ info (getId ls) 2012 "Use find instead of ls to better handle non-alphanumeric filenames."+ where+ for l f =+ let indices = indexOfSublists l (map (headOrDefault "" . oversimplify) commands)+ in do+ mapM_ (f . (\ n -> take (length l) $ drop n commands)) indices+ return . not . null $ indices+ for' l f = for l (first f)+ first func (x:_) = func (getId $ getCommandTokenOrThis x)+ first _ _ = return ()+ hasShortParameter char = any (\x -> "-" `isPrefixOf` x && char `elem` x)+ hasParameter string =+ any (isPrefixOf string . dropWhile (== '-'))+checkPipePitfalls _ _ = return ()++indexOfSublists sub = f 0+ where+ f _ [] = []+ f n a@(r:rest) =+ let others = f (n+1) rest in+ if match sub a+ then n:others+ else others+ match ("?":r1) (_:r2) = match r1 r2+ match (x1:r1) (x2:r2) | x1 == x2 = match r1 r2+ match [] _ = True+ match _ _ = False+++prop_checkShebangParameters1 = verifyTree checkShebangParameters "#!/usr/bin/env bash -x\necho cow"+prop_checkShebangParameters2 = verifyNotTree checkShebangParameters "#! /bin/sh -l "+prop_checkShebangParameters3 = verifyNotTree checkShebangParameters "#!/usr/bin/env -S bash -x\necho cow"+prop_checkShebangParameters4 = verifyNotTree checkShebangParameters "#!/usr/bin/env --split-string bash -x\necho cow"+checkShebangParameters p (T_Annotation _ _ t) = checkShebangParameters p t+checkShebangParameters _ (T_Script _ (T_Literal id sb) _) =+ [makeComment ErrorC id 2096 "On most OS, shebangs can only specify a single parameter." | isMultiWord]+ where+ isMultiWord = length (words sb) > 2 && not (sb `matches` re)+ re = mkRegex "env +(-S|--split-string)"++prop_checkShebang1 = verifyNotTree checkShebang "#!/usr/bin/env bash -x\necho cow"+prop_checkShebang2 = verifyNotTree checkShebang "#! /bin/sh -l "+prop_checkShebang3 = verifyTree checkShebang "ls -l"+prop_checkShebang4 = verifyNotTree checkShebang "#shellcheck shell=sh\nfoo"+prop_checkShebang5 = verifyTree checkShebang "#!/usr/bin/env ash"+prop_checkShebang6 = verifyNotTree checkShebang "#!/usr/bin/env ash\n# shellcheck shell=dash\n"+prop_checkShebang7 = verifyNotTree checkShebang "#!/usr/bin/env ash\n# shellcheck shell=sh\n"+prop_checkShebang8 = verifyTree checkShebang "#!bin/sh\ntrue"+prop_checkShebang9 = verifyNotTree checkShebang "# shellcheck shell=sh\ntrue"+prop_checkShebang10 = verifyNotTree checkShebang "#!foo\n# shellcheck shell=sh ignore=SC2239\ntrue"+prop_checkShebang11 = verifyTree checkShebang "#!/bin/sh/\ntrue"+prop_checkShebang12 = verifyTree checkShebang "#!/bin/sh/ -xe\ntrue"+prop_checkShebang13 = verifyNotTree checkShebang "#!/bin/busybox sh"+prop_checkShebang14 = verifyNotTree checkShebang "#!/bin/busybox sh\n# shellcheck shell=sh\n"+prop_checkShebang15 = verifyNotTree checkShebang "#!/bin/busybox sh\n# shellcheck shell=dash\n"+prop_checkShebang16 = verifyNotTree checkShebang "#!/bin/busybox ash"+prop_checkShebang17 = verifyNotTree checkShebang "#!/bin/busybox ash\n# shellcheck shell=dash\n"+prop_checkShebang18 = verifyNotTree checkShebang "#!/bin/busybox ash\n# shellcheck shell=sh\n"+checkShebang params (T_Annotation _ list t) =+ if any isOverride list then [] else checkShebang params t+ where+ isOverride (ShellOverride _) = True+ isOverride _ = False+checkShebang params (T_Script _ (T_Literal id sb) _) = execWriter $ do+ unless (shellTypeSpecified params) $ do+ when (null sb) $+ err id 2148 "Tips depend on target shell and yours is unknown. Add a shebang or a 'shell' directive."+ when (executableFromShebang sb == "ash") $+ warn id 2187 "Ash scripts will be checked as Dash. Add '# shellcheck shell=dash' to silence."+ unless (null sb) $ do+ unless ("/" `isPrefixOf` sb) $+ err id 2239 "Ensure the shebang uses an absolute path to the interpreter."+ when ("/" `isSuffixOf` head (words sb)) $+ err id 2246 "This shebang specifies a directory. Ensure the interpreter is a file."+++prop_checkForInQuoted = verify checkForInQuoted "for f in \"$(ls)\"; do echo foo; done"+prop_checkForInQuoted2 = verifyNot checkForInQuoted "for f in \"$@\"; do echo foo; done"+prop_checkForInQuoted2a = verifyNot checkForInQuoted "for f in *.mp3; do echo foo; done"+prop_checkForInQuoted2b = verify checkForInQuoted "for f in \"*.mp3\"; do echo foo; done"+prop_checkForInQuoted3 = verify checkForInQuoted "for f in 'find /'; do true; done"+prop_checkForInQuoted4 = verify checkForInQuoted "for f in 1,2,3; do true; done"+prop_checkForInQuoted4a = verifyNot checkForInQuoted "for f in foo{1,2,3}; do true; done"+prop_checkForInQuoted5 = verify checkForInQuoted "for f in ls; do true; done"+prop_checkForInQuoted6 = verifyNot checkForInQuoted "for f in \"${!arr}\"; do true; done"+prop_checkForInQuoted7 = verify checkForInQuoted "for f in ls, grep, mv; do true; done"+prop_checkForInQuoted8 = verify checkForInQuoted "for f in 'ls', 'grep', 'mv'; do true; done"+prop_checkForInQuoted9 = verifyNot checkForInQuoted "for f in 'ls,' 'grep,' 'mv'; do true; done"+checkForInQuoted _ (T_ForIn _ f [T_NormalWord _ [word@(T_DoubleQuoted id list)]] _)+ | any willSplit list && not (mayBecomeMultipleArgs word)+ || maybe False wouldHaveBeenGlob (getLiteralString word) =+ err id 2066 "Since you double quoted this, it will not word split, and the loop will only run once."+checkForInQuoted _ (T_ForIn _ f [T_NormalWord _ [T_SingleQuoted id _]] _) =+ warn id 2041 "This is a literal string. To run as a command, use $(..) instead of '..' . "+checkForInQuoted _ (T_ForIn _ _ [single] _)+ | maybe False (',' `elem`) $ getUnquotedLiteral single =+ warn (getId single) 2042 "Use spaces, not commas, to separate loop elements."+ | not (willSplit single || mayBecomeMultipleArgs single) =+ warn (getId single) 2043 "This loop will only ever run once. Bad quoting or missing glob/expansion?"+checkForInQuoted params (T_ForIn _ _ multiple _) =+ forM_ multiple $ \arg -> sequence_ $ do+ suffix <- getTrailingUnquotedLiteral arg+ string <- getLiteralString suffix+ guard $ "," `isSuffixOf` string+ return $+ warnWithFix (getId arg) 2258+ "The trailing comma is part of the value, not a separator. Delete or quote it."+ (fixWith [replaceEnd (getId suffix) params 1 ""])+checkForInQuoted _ _ = return ()++prop_checkForInCat1 = verify checkForInCat "for f in $(cat foo); do stuff; done"+prop_checkForInCat1a = verify checkForInCat "for f in `cat foo`; do stuff; done"+prop_checkForInCat2 = verify checkForInCat "for f in $(cat foo | grep lol); do stuff; done"+prop_checkForInCat2a = verify checkForInCat "for f in `cat foo | grep lol`; do stuff; done"+prop_checkForInCat3 = verifyNot checkForInCat "for f in $(cat foo | grep bar | wc -l); do stuff; done"+checkForInCat _ (T_ForIn _ f [T_NormalWord _ w] _) = mapM_ checkF w+ where+ checkF (T_DollarExpansion id [T_Pipeline _ _ r])+ | all isLineBased r =+ info id 2013 "To read lines rather than words, pipe/redirect to a 'while read' loop."+ checkF (T_Backticked id cmds) = checkF (T_DollarExpansion id cmds)+ checkF _ = return ()+ isLineBased cmd = any (cmd `isCommand`)+ ["grep", "fgrep", "egrep", "sed", "cat", "awk", "cut", "sort"]+checkForInCat _ _ = return ()++prop_checkForInLs = verify checkForInLs "for f in $(ls *.mp3); do mplayer \"$f\"; done"+prop_checkForInLs2 = verify checkForInLs "for f in `ls *.mp3`; do mplayer \"$f\"; done"+prop_checkForInLs3 = verify checkForInLs "for f in `find / -name '*.mp3'`; do mplayer \"$f\"; done"+checkForInLs _ = try+ where+ try (T_ForIn _ f [T_NormalWord _ [T_DollarExpansion id [x]]] _) =+ check id f x+ try (T_ForIn _ f [T_NormalWord _ [T_Backticked id [x]]] _) =+ check id f x+ try _ = return ()+ check id f x =+ case oversimplify x of+ ("ls":n) ->+ let warntype = if any ("-" `isPrefixOf`) n then warn else err in+ warntype id 2045 "Iterating over ls output is fragile. Use globs."+ ("find":_) -> warn id 2044 "For loops over find output are fragile. Use find -exec or a while read loop."+ _ -> return ()+++prop_checkFindExec1 = verify checkFindExec "find / -name '*.php' -exec rm {};"+prop_checkFindExec2 = verify checkFindExec "find / -exec touch {} && ls {} \\;"+prop_checkFindExec3 = verify checkFindExec "find / -execdir cat {} | grep lol +"+prop_checkFindExec4 = verifyNot checkFindExec "find / -name '*.php' -exec foo {} +"+prop_checkFindExec5 = verifyNot checkFindExec "find / -execdir bash -c 'a && b' \\;"+prop_checkFindExec6 = verify checkFindExec "find / -type d -execdir rm *.jpg \\;"+checkFindExec _ cmd@(T_SimpleCommand _ _ t@(h:r)) | cmd `isCommand` "find" = do+ c <- broken r False+ when c $+ let wordId = getId $ last t in+ err wordId 2067 "Missing ';' or + terminating -exec. You can't use |/||/&&, and ';' has to be a separate, quoted argument."++ where+ broken [] v = return v+ broken (w:r) v = do+ when v (mapM_ warnFor $ fromWord w)+ case getLiteralString w of+ Just "-exec" -> broken r True+ Just "-execdir" -> broken r True -- n.b. -execdir ;/+ is not defined in POSIX+ Just "-ok" -> broken r True -- n.b. -ok + is not defined in POSIX+ Just "-okdir" -> broken r True -- n.b. -okdir ;/+ is not defined in POSIX+ Just "+" -> broken r False+ Just ";" -> broken r False+ _ -> broken r v++ shouldWarn x =+ case x of+ T_DollarExpansion _ _ -> True+ T_Backticked _ _ -> True+ T_Glob _ _ -> True+ T_Extglob {} -> True+ _ -> False++ warnFor x =+ when(shouldWarn x) $+ info (getId x) 2014 "This will expand once before find runs, not per file found."++ fromWord (T_NormalWord _ l) = l+ fromWord _ = []+checkFindExec _ _ = return ()+++prop_checkUnquotedExpansions1 = verify checkUnquotedExpansions "rm $(ls)"+prop_checkUnquotedExpansions1a = verify checkUnquotedExpansions "rm `ls`"+prop_checkUnquotedExpansions2 = verify checkUnquotedExpansions "rm foo$(date)"+prop_checkUnquotedExpansions3 = verify checkUnquotedExpansions "[ $(foo) == cow ]"+prop_checkUnquotedExpansions3a = verify checkUnquotedExpansions "[ ! $(foo) ]"+prop_checkUnquotedExpansions4 = verifyNot checkUnquotedExpansions "[[ $(foo) == cow ]]"+prop_checkUnquotedExpansions5 = verifyNot checkUnquotedExpansions "for f in $(cmd); do echo $f; done"+prop_checkUnquotedExpansions6 = verifyNot checkUnquotedExpansions "$(cmd)"+prop_checkUnquotedExpansions7 = verifyNot checkUnquotedExpansions "cat << foo\n$(ls)\nfoo"+prop_checkUnquotedExpansions8 = verifyNot checkUnquotedExpansions "set -- $(seq 1 4)"+prop_checkUnquotedExpansions9 = verifyNot checkUnquotedExpansions "echo foo `# inline comment`"+prop_checkUnquotedExpansions10 = verify checkUnquotedExpansions "#!/bin/sh\nexport var=$(val)"+prop_checkUnquotedExpansions11 = verifyNot checkUnquotedExpansions "ps -p $(pgrep foo)"+checkUnquotedExpansions params =+ check+ where+ check t@(T_DollarExpansion _ c) = examine t c+ check t@(T_Backticked _ c) = examine t c+ check t@(T_DollarBraceCommandExpansion _ _ c) = examine t c+ check _ = return ()+ tree = parentMap params+ examine t contents =+ unless (null contents || shouldBeSplit t || isQuoteFree (shellType params) tree t || usedAsCommandName tree t) $+ warn (getId t) 2046 "Quote this to prevent word splitting."++ shouldBeSplit t =+ getCommandNameFromExpansion t `elem` [Just "seq", Just "pgrep"]+++prop_checkRedirectToSame = verify checkRedirectToSame "cat foo > foo"+prop_checkRedirectToSame2 = verify checkRedirectToSame "cat lol | sed -e 's/a/b/g' > lol"+prop_checkRedirectToSame3 = verifyNot checkRedirectToSame "cat lol | sed -e 's/a/b/g' > foo.bar && mv foo.bar lol"+prop_checkRedirectToSame4 = verifyNot checkRedirectToSame "foo /dev/null > /dev/null"+prop_checkRedirectToSame5 = verifyNot checkRedirectToSame "foo > bar 2> bar"+prop_checkRedirectToSame6 = verifyNot checkRedirectToSame "echo foo > foo"+prop_checkRedirectToSame7 = verifyNot checkRedirectToSame "sed 's/foo/bar/g' file | sponge file"+prop_checkRedirectToSame8 = verifyNot checkRedirectToSame "while read -r line; do _=\"$fname\"; done <\"$fname\""+prop_checkRedirectToSame9 = verifyNot checkRedirectToSame "while read -r line; do cat < \"$fname\"; done <\"$fname\""+prop_checkRedirectToSame10 = verifyNot checkRedirectToSame "mapfile -t foo <foo"+checkRedirectToSame params s@(T_Pipeline _ _ list) =+ mapM_ (\l -> (mapM_ (\x -> doAnalysis (checkOccurrences x) l) (getAllRedirs list))) list+ where+ note x = makeComment InfoC x 2094+ "Make sure not to read and write the same file in the same pipeline."+ checkOccurrences t@(T_NormalWord exceptId x) u@(T_NormalWord newId y) |+ exceptId /= newId+ && x == y+ && not (isInput t && isInput u)+ && not (isOutput t && isOutput u)+ && not (special t)+ && not (any isHarmlessCommand [t,u])+ && not (any containsAssignment [u]) = do+ addComment $ note newId+ addComment $ note exceptId+ checkOccurrences _ _ = return ()+ getAllRedirs = concatMap (\t ->+ case t of+ T_Redirecting _ ls _ -> concatMap getRedirs ls+ _ -> [])+ getRedirs (T_FdRedirect _ _ (T_IoFile _ op file)) =+ case op of T_Greater _ -> [file]+ T_Less _ -> [file]+ T_DGREAT _ -> [file]+ _ -> []+ getRedirs _ = []+ special x = "/dev/" `isPrefixOf` concat (oversimplify x)+ isInput t =+ case NE.tail $ getPath (parentMap params) t of+ T_IoFile _ op _:_ ->+ case op of+ T_Less _ -> True+ _ -> False+ _ -> False+ isOutput t =+ case NE.tail $ getPath (parentMap params) t of+ T_IoFile _ op _:_ ->+ case op of+ T_Greater _ -> True+ T_DGREAT _ -> True+ _ -> False+ _ -> False+ isHarmlessCommand arg = fromMaybe False $ do+ cmd <- getClosestCommand (parentMap params) arg+ name <- getCommandBasename cmd+ return $ name `elem` ["echo", "mapfile", "printf", "sponge"]+ containsAssignment arg = fromMaybe False $ do+ cmd <- getClosestCommand (parentMap params) arg+ return $ isAssignment cmd++checkRedirectToSame _ _ = return ()+++prop_checkShorthandIf = verify checkShorthandIf "[[ ! -z file ]] && scp file host || rm file"+prop_checkShorthandIf2 = verifyNot checkShorthandIf "[[ ! -z file ]] && { scp file host || echo 'Eek'; }"+prop_checkShorthandIf3 = verifyNot checkShorthandIf "foo && bar || echo baz"+prop_checkShorthandIf4 = verifyNot checkShorthandIf "foo && a=b || a=c"+prop_checkShorthandIf5 = verifyNot checkShorthandIf "foo && rm || printf b"+prop_checkShorthandIf6 = verifyNot checkShorthandIf "if foo && bar || baz; then true; fi"+prop_checkShorthandIf7 = verifyNot checkShorthandIf "while foo && bar || baz; do true; done"+prop_checkShorthandIf8 = verify checkShorthandIf "if true; then foo && bar || baz; fi"+prop_checkShorthandIf9 = verifyNot checkShorthandIf "foo && [ -x /file ] || bar"+prop_checkShorthandIf10 = verifyNot checkShorthandIf "foo && bar || true"+prop_checkShorthandIf11 = verify checkShorthandIf "foo && bar || false"+checkShorthandIf params x@(T_OrIf _ (T_AndIf id _ b) (T_Pipeline _ _ t))+ | not (isOk t || inCondition) && not (isTestCommand b) =+ info id 2015 "Note that A && B || C is not if-then-else. C may run when A is true."+ where+ isOk [t] = isAssignment t || fromMaybe False (do+ name <- getCommandBasename t+ return $ name `elem` ["echo", "exit", "return", "printf", "true", ":"])+ isOk _ = False+ inCondition = isCondition $ getPath (parentMap params) x+checkShorthandIf _ _ = return ()+++prop_checkDollarStar = verify checkDollarStar "for f in $*; do ..; done"+prop_checkDollarStar2 = verifyNot checkDollarStar "a=$*"+prop_checkDollarStar3 = verifyNot checkDollarStar "[[ $* = 'a b' ]]"+prop_checkDollarStar4 = verify checkDollarStar "for f in ${var[*]}; do ..; done"+prop_checkDollarStar5 = verify checkDollarStar "ls ${*//foo/bar}"+prop_checkDollarStar6 = verify checkDollarStar "ls ${var[*]%%.*}"+prop_checkDollarStar7 = verify checkDollarStar "ls ${*}"+prop_checkDollarStar8 = verifyNot checkDollarStar "ls ${#*}"+prop_checkDollarStar9 = verify checkDollarStar "ls ${arr[*]}"+prop_checkDollarStar10 = verifyNot checkDollarStar "ls ${#arr[*]}"+checkDollarStar p t@(T_NormalWord _ [T_DollarBraced id _ l])+ | not (isStrictlyQuoteFree (shellType p) (parentMap p) t) = do+ let str = concat (oversimplify l)+ when ("*" `isPrefixOf` str) $+ warn id 2048 "Use \"$@\" (with quotes) to prevent whitespace problems."+ when ("[*]" `isPrefixOf` (getBracedModifier str) && isVariableChar (headOrDefault '!' str)) $+ warn id 2048 "Use \"${array[@]}\" (with quotes) to prevent whitespace problems."++checkDollarStar _ _ = return ()+++prop_checkUnquotedDollarAt = verify checkUnquotedDollarAt "ls $@"+prop_checkUnquotedDollarAt1 = verifyNot checkUnquotedDollarAt "ls ${#@}"+prop_checkUnquotedDollarAt2 = verify checkUnquotedDollarAt "ls ${foo[@]}"+prop_checkUnquotedDollarAt3 = verifyNot checkUnquotedDollarAt "ls ${#foo[@]}"+prop_checkUnquotedDollarAt4 = verifyNot checkUnquotedDollarAt "ls \"$@\""+prop_checkUnquotedDollarAt5 = verifyNot checkUnquotedDollarAt "ls ${foo/@/ at }"+prop_checkUnquotedDollarAt6 = verifyNot checkUnquotedDollarAt "a=$@"+prop_checkUnquotedDollarAt7 = verify checkUnquotedDollarAt "for f in ${var[@]}; do true; done"+prop_checkUnquotedDollarAt8 = verifyNot checkUnquotedDollarAt "echo \"${args[@]:+${args[@]}}\""+prop_checkUnquotedDollarAt9 = verifyNot checkUnquotedDollarAt "echo ${args[@]:+\"${args[@]}\"}"+prop_checkUnquotedDollarAt10 = verifyNot checkUnquotedDollarAt "echo ${@+\"$@\"}"+checkUnquotedDollarAt p word@(T_NormalWord _ parts) | not $ isStrictlyQuoteFree (shellType p) (parentMap p) word =+ forM_ (find isArrayExpansion parts) $ \x ->+ unless (isQuotedAlternativeReference x) $+ err (getId x) 2068+ "Double quote array expansions to avoid re-splitting elements."+checkUnquotedDollarAt _ _ = return ()++prop_checkConcatenatedDollarAt1 = verify checkConcatenatedDollarAt "echo \"foo$@\""+prop_checkConcatenatedDollarAt2 = verify checkConcatenatedDollarAt "echo ${arr[@]}lol"+prop_checkConcatenatedDollarAt3 = verify checkConcatenatedDollarAt "echo $a$@"+prop_checkConcatenatedDollarAt4 = verifyNot checkConcatenatedDollarAt "echo $@"+prop_checkConcatenatedDollarAt5 = verifyNot checkConcatenatedDollarAt "echo \"${arr[@]}\""+prop_checkConcatenatedDollarAt6 = verifyNot checkConcatenatedDollarAt $ unlines ["echo \"${@}\"\\", " | cat"]+prop_checkConcatenatedDollarAt7 = verifyNot checkConcatenatedDollarAt $ unlines ["echo \"${arr[@]}\"\\", " other"]+prop_checkConcatenatedDollarAt8 = verify checkConcatenatedDollarAt "echo \"$@\"''"+checkConcatenatedDollarAt p word@T_NormalWord {}+ | not $ isQuoteFree (shellType p) (parentMap p) word+ || null (drop 1 parts) =+ mapM_ for array+ where+ -- Escaped linefeeds can leave empty unquoted literals in the word.+ parts = filter hasContent $ getWordParts word+ hasContent (T_Literal _ "") = False+ hasContent _ = True+ array = find isArrayExpansion parts+ for t = err (getId t) 2145 "Argument mixes string and array. Use * or separate argument."+checkConcatenatedDollarAt _ _ = return ()++prop_checkArrayAsString1 = verify checkArrayAsString "a=$@"+prop_checkArrayAsString2 = verify checkArrayAsString "a=\"${arr[@]}\""+prop_checkArrayAsString3 = verify checkArrayAsString "a=*.png"+prop_checkArrayAsString4 = verify checkArrayAsString "a={1..10}"+prop_checkArrayAsString5 = verifyNot checkArrayAsString "a='*.gif'"+prop_checkArrayAsString6 = verifyNot checkArrayAsString "a=$*"+prop_checkArrayAsString7 = verifyNot checkArrayAsString "a=( $@ )"+checkArrayAsString _ (T_Assignment id _ _ _ word) =+ if willConcatInAssignment word+ then+ warn (getId word) 2124+ "Assigning an array to a string! Assign as array, or use * instead of @ to concatenate."+ else+ when (willBecomeMultipleArgs word) $+ warn (getId word) 2125+ "Brace expansions and globs are literal in assignments. Quote it or use an array."+checkArrayAsString _ _ = return ()++prop_checkArrayWithoutIndex1 = verifyTree checkArrayWithoutIndex "foo=(a b); echo $foo"+prop_checkArrayWithoutIndex2 = verifyNotTree checkArrayWithoutIndex "foo='bar baz'; foo=($foo); echo ${foo[0]}"+prop_checkArrayWithoutIndex3 = verifyTree checkArrayWithoutIndex "coproc foo while true; do echo cow; done; echo $foo"+prop_checkArrayWithoutIndex4 = verifyTree checkArrayWithoutIndex "coproc tail -f log; echo $COPROC"+prop_checkArrayWithoutIndex5 = verifyTree checkArrayWithoutIndex "a[0]=foo; echo $a"+prop_checkArrayWithoutIndex6 = verifyTree checkArrayWithoutIndex "echo $PIPESTATUS"+prop_checkArrayWithoutIndex7 = verifyTree checkArrayWithoutIndex "a=(a b); a+=c"+prop_checkArrayWithoutIndex8 = verifyTree checkArrayWithoutIndex "declare -a foo; foo=bar;"+prop_checkArrayWithoutIndex9 = verifyTree checkArrayWithoutIndex "read -r -a arr <<< 'foo bar'; echo \"$arr\""+prop_checkArrayWithoutIndex10 = verifyTree checkArrayWithoutIndex "read -ra arr <<< 'foo bar'; echo \"$arr\""+prop_checkArrayWithoutIndex11 = verifyNotTree checkArrayWithoutIndex "read -rpfoobar r; r=42"+prop_checkArrayWithoutIndex12 = verifyNotTree checkArrayWithoutIndex "#!/bin/sh\nPIPESTATUS=foo"+checkArrayWithoutIndex params _ =+ doVariableFlowAnalysis readF writeF defaultSet (variableFlow params)+ where+ defaultSet = S.fromList $ if shellType params == Bash then arrayVariables else []+ readF _ (T_DollarBraced id _ token) _ = do+ s <- get+ return . maybeToList $ do+ name <- getLiteralString token+ guard $ S.member name s+ return $ makeComment WarningC id 2128+ "Expanding an array without an index only gives the first element."+ readF _ _ _ = return []++ writeF _ (T_Assignment id mode name [] _) _ (DataString _) = do+ isArray <- gets (S.member name)+ return $ if not isArray then [] else+ case mode of+ Assign -> [makeComment WarningC id 2178 "Variable was used as an array but is now assigned a string."]+ Append -> [makeComment WarningC id 2179 "Use array+=(\"item\") to append items to an array."]++ writeF _ t name (DataArray _) = do+ modify (S.insert name)+ return []+ writeF _ expr name _ = do+ if isIndexed expr+ then modify (S.insert name)+ else modify (S.delete name)+ return []++ isIndexed expr =+ case expr of+ T_Assignment _ _ _ (_:_) _ -> True+ _ -> False++prop_checkStderrRedirect = verify checkStderrRedirect "test 2>&1 > cow"+prop_checkStderrRedirect2 = verifyNot checkStderrRedirect "test > cow 2>&1"+prop_checkStderrRedirect3 = verifyNot checkStderrRedirect "test 2>&1 > file | grep stderr"+prop_checkStderrRedirect4 = verifyNot checkStderrRedirect "errors=$(test 2>&1 > file)"+prop_checkStderrRedirect5 = verifyNot checkStderrRedirect "read < <(test 2>&1 > file)"+prop_checkStderrRedirect6 = verify checkStderrRedirect "foo | bar 2>&1 > /dev/null"+prop_checkStderrRedirect7 = verifyNot checkStderrRedirect "{ cmd > file; } 2>&1"+checkStderrRedirect params redir@(T_Redirecting _ [+ T_FdRedirect id "2" (T_IoDuplicate _ (T_GREATAND _) "1"),+ T_FdRedirect _ _ (T_IoFile _ op _)+ ] _) = case op of+ T_Greater _ -> error+ T_DGREAT _ -> error+ _ -> return ()+ where+ usesOutput t =+ case t of+ (T_Pipeline _ _ list) -> length list > 1 && not (isParentOf (parentMap params) (last list) redir)+ T_ProcSub {} -> True+ T_DollarExpansion {} -> True+ T_Backticked {} -> True+ _ -> False+ isCaptured = any usesOutput $ getPath (parentMap params) redir++ error = unless isCaptured $+ warn id 2069 "To redirect stdout+stderr, 2>&1 must be last (or use '{ cmd > file; } 2>&1' to clarify)."++checkStderrRedirect _ _ = return ()++lt x = trace ("Tracing " ++ show x) x -- STRIP+ltt t = trace ("Tracing " ++ show t) -- STRIP+++prop_checkSingleQuotedVariables = verify checkSingleQuotedVariables "echo '$foo'"+prop_checkSingleQuotedVariables2 = verify checkSingleQuotedVariables "echo 'lol$1.jpg'"+prop_checkSingleQuotedVariables3 = verifyNot checkSingleQuotedVariables "sed 's/foo$/bar/'"+prop_checkSingleQuotedVariables3a = verify checkSingleQuotedVariables "sed 's/${foo}/bar/'"+prop_checkSingleQuotedVariables3b = verify checkSingleQuotedVariables "sed 's/$(echo cow)/bar/'"+prop_checkSingleQuotedVariables3c = verify checkSingleQuotedVariables "sed 's/$((1+foo))/bar/'"+prop_checkSingleQuotedVariables4 = verifyNot checkSingleQuotedVariables "awk '{print $1}'"+prop_checkSingleQuotedVariables5 = verifyNot checkSingleQuotedVariables "trap 'echo $SECONDS' EXIT"+prop_checkSingleQuotedVariables6 = verifyNot checkSingleQuotedVariables "sed -n '$p'"+prop_checkSingleQuotedVariables6a = verify checkSingleQuotedVariables "sed -n '$pattern'"+prop_checkSingleQuotedVariables6b = verifyNot checkSingleQuotedVariables "sed -n -e '/foo/h; ${ g; }'"+prop_checkSingleQuotedVariables6c = verifyNot checkSingleQuotedVariables "sed -e '${a\\\nEOF' -e '}'"+prop_checkSingleQuotedVariables6d = verifyNot checkSingleQuotedVariables "sed -n -e '/0$/h; 42,${' -e G -e '}'"+prop_checkSingleQuotedVariables7 = verifyNot checkSingleQuotedVariables "PS1='$PWD \\$ '"+prop_checkSingleQuotedVariables8 = verify checkSingleQuotedVariables "find . -exec echo '$1' {} +"+prop_checkSingleQuotedVariables9 = verifyNot checkSingleQuotedVariables "find . -exec awk '{print $1}' {} \\;"+prop_checkSingleQuotedVariables10 = verify checkSingleQuotedVariables "echo '`pwd`'"+prop_checkSingleQuotedVariables11 = verifyNot checkSingleQuotedVariables "sed '${/lol/d}'"+prop_checkSingleQuotedVariables12 = verifyNot checkSingleQuotedVariables "eval 'echo $1'"+prop_checkSingleQuotedVariables13 = verifyNot checkSingleQuotedVariables "busybox awk '{print $1}'"+prop_checkSingleQuotedVariables14 = verifyNot checkSingleQuotedVariables "[ -v 'bar[$foo]' ]"+prop_checkSingleQuotedVariables15 = verifyNot checkSingleQuotedVariables "git filter-branch 'test $GIT_COMMIT'"+prop_checkSingleQuotedVariables16 = verify checkSingleQuotedVariables "git '$a'"+prop_checkSingleQuotedVariables17 = verifyNot checkSingleQuotedVariables "rename 's/(.)a/$1/g' *"+prop_checkSingleQuotedVariables18 = verifyNot checkSingleQuotedVariables "echo '``'"+prop_checkSingleQuotedVariables19 = verifyNot checkSingleQuotedVariables "echo '```'"+prop_checkSingleQuotedVariables20 = verifyNot checkSingleQuotedVariables "mumps -run %XCMD 'W $O(^GLOBAL(5))'"+prop_checkSingleQuotedVariables21 = verifyNot checkSingleQuotedVariables "mumps -run LOOP%XCMD --xec 'W $O(^GLOBAL(6))'"+prop_checkSingleQuotedVariables22 = verifyNot checkSingleQuotedVariables "jq '$__loc__'"+prop_checkSingleQuotedVariables23 = verifyNot checkSingleQuotedVariables "command jq '$__loc__'"+prop_checkSingleQuotedVariables24 = verifyNot checkSingleQuotedVariables "exec jq '$__loc__'"+prop_checkSingleQuotedVariables25 = verifyNot checkSingleQuotedVariables "exec -c -a foo jq '$__loc__'"+prop_checkSingleQuotedVariables26 = verifyNot checkSingleQuotedVariables "runc exec ctr sh -c 'echo $HOME'"+prop_checkSingleQuotedVariables27 = verifyNot checkSingleQuotedVariables "run -0 nsenter -t 1 -m /bin/bash -eu -o pipefail -c 'echo $HOME'"+prop_checkSingleQuotedVariables28 = verifyNot checkSingleQuotedVariables "kubectl exec pod -- sh -euc 'echo $HOME'"+prop_checkSingleQuotedVariables29 = verify checkSingleQuotedVariables "runc exec ctr sh -c 'echo $HOME' 'echo $HOME'"+prop_checkSingleQuotedVariables30 = verify checkSingleQuotedVariables "runc exec ctr sh -x 'echo $HOME'"+prop_checkSingleQuotedVariables31 = verify checkSingleQuotedVariables "runc exec ctr sh script -c 'echo $HOME'"+prop_checkSingleQuotedVariables32 = verify checkSingleQuotedVariables "echo sh --rcfile 'echo $HOME'"+prop_checkSingleQuotedVariables33 = verifyNot checkSingleQuotedVariables "chroot /mnt /bin/ksh93 -c 'echo $HOME'"+prop_checkSingleQuotedVariables34 = verifyNot checkSingleQuotedVariables "yq '.a as $x | $x'"+++checkSingleQuotedVariables params t@(T_SingleQuoted id s) =+ when (s `matches` re) $+ if "sed" == commandName+ then unless (s `matches` sedContra) showMessage+ else unless isProbablyOk showMessage+ where+ parents = parentMap params+ showMessage = info id 2016+ "Expressions don't expand in single quotes, use double quotes for that."+ commandName = fromMaybe "" $ do+ cmd <- getClosestCommand parents t+ name <- getCommandBasename cmd+ return $ if name == "find" then getFindCommand cmd else if name == "git" then getGitCommand cmd else if name == "mumps" then getMumpsCommand cmd else name++ isProbablyOk =+ any isOkAssignment (NE.take 3 $ getPath parents t)+ || commandName `elem` [+ "trap"+ ,"sh"+ ,"bash"+ ,"ksh"+ ,"zsh"+ ,"ssh"+ ,"eval"+ ,"xprop"+ ,"alias"+ ,"sudo" -- covering "sudo sh" and such+ ,"doas" -- same as sudo+ ,"run0" -- same as sudo+ ,"docker" -- like above+ ,"podman"+ ,"oc"+ ,"dpkg-query"+ ,"jq" -- could also check that user provides --arg+ ,"yq"+ ,"rename"+ ,"rg"+ ,"unset"+ ,"git filter-branch"+ ,"mumps -run %XCMD"+ ,"mumps -run LOOP%XCMD"+ ]+ || "awk" `isSuffixOf` commandName+ || "perl" `isPrefixOf` commandName+ || isShellScriptArgument++ -- Like `runc exec ctr sh -c 'echo $HOME'`+ isShellScriptArgument = fromMaybe False $ do+ T_Redirecting _ _ (T_SimpleCommand _ _ words) <- getClosestCommand parents t+ let pathIds = map getId $ NE.toList $ getPath parents t+ let before = takeWhile (\w -> getId w `notElem` pathIds) words+ return $ any isShellInvocation $ tails $ map (fromMaybe "" . getLiteralString) before+ isShellInvocation (cmd:opts) =+ basename cmd `elem` ["sh", "bash", "dash", "ash", "ksh", "ksh88", "ksh93", "mksh", "oksh", "zsh"] && endsWithDashC opts+ isShellInvocation _ = False+ endsWithDashC opts =+ case opts of+ [flag] -> flag `matches` mkRegex "^-[a-zA-Z]*c[a-zA-Z]*$"+ flag:_:rest | flag `elem` ["-o", "+o", "-O", "+O"] -> endsWithDashC rest+ flag:rest | take 1 flag `elem` ["-", "+"] -> endsWithDashC rest+ _ -> False++ commonlyQuoted = ["PS1", "PS2", "PS3", "PS4", "PROMPT_COMMAND"]+ isOkAssignment t =+ case t of+ T_Assignment _ _ name _ _ -> name `elem` commonlyQuoted+ TC_Unary _ _ "-v" _ -> True+ _ -> False++ re = mkRegex "\\$[{(0-9a-zA-Z_]|`[^`]+`"+ sedContra = mkRegex "\\$[acdgGilpPsxy]($|[^a-zA-Z])|\\$\\{[[:space:]]*($|/|[acdgGilpPsxy]($|[^a-zA-Z]))"++ getFindCommand (T_SimpleCommand _ _ words) =+ let list = map getLiteralString words+ cmd = dropWhile (\x -> x `notElem` map Just ["-exec", "-execdir", "-ok", "-okdir"]) list+ in+ case cmd of+ (flag:cmd:rest) -> fromMaybe "find" cmd+ _ -> "find"+ getFindCommand (T_Redirecting _ _ cmd) = getFindCommand cmd+ getFindCommand _ = "find"+ getGitCommand (T_SimpleCommand _ _ words) =+ case map getLiteralString words of+ Just "git":Just "filter-branch":_ -> "git filter-branch"+ _ -> "git"+ getGitCommand (T_Redirecting _ _ cmd) = getGitCommand cmd+ getGitCommand _ = "git"+ getMumpsCommand (T_SimpleCommand _ _ words) =+ case map getLiteralString words of+ Just "mumps":Just "-run":Just "%XCMD":_ -> "mumps -run %XCMD"+ Just "mumps":Just "-run":Just "LOOP%XCMD":_ -> "mumps -run LOOP%XCMD"+ _ -> "mumps"+ getMumpsCommand (T_Redirecting _ _ cmd) = getMumpsCommand cmd+ getMumpsCommand _ = "mumps"+checkSingleQuotedVariables _ _ = return ()+++prop_checkUnquotedN = verify checkUnquotedN "if [ -n $foo ]; then echo cow; fi"+prop_checkUnquotedN2 = verify checkUnquotedN "[ -n $cow ]"+prop_checkUnquotedN3 = verifyNot checkUnquotedN "[[ -n $foo ]] && echo cow"+prop_checkUnquotedN4 = verify checkUnquotedN "[ -n $cow -o -t 1 ]"+prop_checkUnquotedN5 = verifyNot checkUnquotedN "[ -n \"$@\" ]"+checkUnquotedN _ (TC_Unary _ SingleBracket "-n" t) | willSplit t =+ unless (any isArrayExpansion $ getWordParts t) $ -- There's SC2198 for these+ err (getId t) 2070 "-n doesn't work with unquoted arguments. Quote or use [[ ]]."+checkUnquotedN _ _ = return ()++prop_checkNumberComparisons1 = verify checkNumberComparisons "[[ $foo < 3 ]]"+prop_checkNumberComparisons2 = verify checkNumberComparisons "[[ 0 >= $(cmd) ]]"+prop_checkNumberComparisons3 = verifyNot checkNumberComparisons "[[ $foo ]] > 3"+prop_checkNumberComparisons4 = verify checkNumberComparisons "[[ $foo > 2.72 ]]"+prop_checkNumberComparisons5 = verify checkNumberComparisons "[[ $foo -le 2.72 ]]"+prop_checkNumberComparisons6 = verify checkNumberComparisons "[[ 3.14 -eq $foo ]]"+prop_checkNumberComparisons7 = verifyNot checkNumberComparisons "[[ 3.14 == $foo ]]"+prop_checkNumberComparisons8 = verify checkNumberComparisons "[ foo <= bar ]"+prop_checkNumberComparisons9 = verify checkNumberComparisons "[ foo \\>= bar ]"+prop_checkNumberComparisons11 = verify checkNumberComparisons "[ $foo -eq 'N' ]"+prop_checkNumberComparisons12 = verify checkNumberComparisons "[ x$foo -gt x${N} ]"+prop_checkNumberComparisons13 = verify checkNumberComparisons "[ $foo > $bar ]"+prop_checkNumberComparisons14 = verifyNot checkNumberComparisons "[[ foo < bar ]]"+prop_checkNumberComparisons15 = verifyNot checkNumberComparisons "[ $foo '>' $bar ]"+prop_checkNumberComparisons16 = verify checkNumberComparisons "[ foo -eq 'y' ]"+prop_checkNumberComparisons17 = verify checkNumberComparisons "[[ 'foo' -eq 2 ]]"+prop_checkNumberComparisons18 = verify checkNumberComparisons "[[ foo -eq 2 ]]"+prop_checkNumberComparisons19 = verifyNot checkNumberComparisons "foo=1; [[ foo -eq 2 ]]"+prop_checkNumberComparisons20 = verify checkNumberComparisons "[[ 2 -eq / ]]"+prop_checkNumberComparisons21 = verify checkNumberComparisons "[[ foo -eq foo ]]"+prop_checkNumberComparisons22 = verify checkNumberComparisons "x=10; [[ $x > $z ]]"+prop_checkNumberComparisons23 = verify checkNumberComparisons "x=0; if [[ -n $def ]]; then x=$def; fi; while [ $x > $z ]; do lol; done"+prop_checkNumberComparisons24 = verify checkNumberComparisons "x=$RANDOM; [ $x > $z ]"+prop_checkNumberComparisons25 = verify checkNumberComparisons "[[ $((n++)) > $x ]]"++checkNumberComparisons params (TC_Binary id typ op lhs rhs) = do+ if isNum lhs || isNum rhs+ then do+ when (isLtGt op) $+ err id 2071 $+ op ++ " is for string comparisons. Use " ++ eqv op ++ " instead."+ when (isLeGe op && hasStringComparison) $+ err id 2071 $ op ++ " is not a valid operator. " +++ "Use " ++ eqv op ++ " ."+ else do+ when (isLeGe op || isLtGt op) $+ mapM_ checkDecimals [lhs, rhs]++ when (isLeGe op && hasStringComparison) $+ err id 2122 $ op ++ " is not a valid operator. " +++ "Use '! a " ++ esc ++ invert op ++ " b' instead."++ when (typ == SingleBracket && op `elem` ["<", ">"]) $+ case shellType params of+ Sh -> return () -- These are unsupported and will be caught by bashism checks.+ Dash -> err id 2073 $ "Escape \\" ++ op ++ " to prevent it redirecting."+ BusyboxSh -> err id 2073 $ "Escape \\" ++ op ++ " to prevent it redirecting."+ _ -> err id 2073 $ "Escape \\" ++ op ++ " to prevent it redirecting (or switch to [[ .. ]])."++ when (op `elem` arithmeticBinaryTestOps) $ do+ mapM_ checkDecimals [lhs, rhs]+ mapM_ checkString [lhs, rhs]+++ where+ hasStringComparison = shellType params /= Sh+ isLtGt = flip elem ["<", "\\<", ">", "\\>"]+ isLeGe = flip elem ["<=", "\\<=", ">=", "\\>="]++ checkDecimals hs =+ when (isFraction hs && not (hasFloatingPoint params)) $+ err (getId hs) 2072 decimalError+ decimalError = "Decimals are not supported. " +++ "Either use integers only, or use bc or awk to compare."++ checkString t =+ let+ asString = getLiteralStringDef "\0" t+ isVar = isVariableName asString+ kind = if isVar then "a variable" else "an arithmetic expression"+ fix = if isVar then "$var" else "$((expr))"+ in+ when (isNonNum t) $+ if typ == SingleBracket+ then+ err (getId t) 2170 $+ "Invalid number for " ++ op ++ ". Use " ++ seqv op +++ " to compare as string (or use " ++ fix +++ " to expand as " ++ kind ++ ")."+ else+ -- We should warn if any of the following holds:+ -- The string is not a variable name+ -- Any part of it is quoted+ -- It's not a recognized variable name+ when (not isVar || any isQuotes (getWordParts t) || asString `notElem` assignedVariables) $+ warn (getId t) 2309 $+ op ++ " treats this as " ++ kind ++ ". " +++ "Use " ++ seqv op ++ " to compare as string (or expand explicitly with " ++ fix ++ ")."++ assignedVariables :: [String]+ assignedVariables = mapMaybe f (variableFlow params)+ where+ f t = do+ Assignment (_, _, name, _) <- return t+ return name++ isNonNum t = not . all numChar $ onlyLiteralString t+ numChar x = isDigit x || x `elem` "+-. "++ isNum t =+ case getWordParts t of+ [T_DollarArithmetic {}] -> True+ [b@(T_DollarBraced id _ c)] ->+ let+ str = concat $ oversimplify c+ var = getBracedReference str+ in fromMaybe False $ do+ cfga <- cfgAnalysis params+ state <- CF.getIncomingState cfga id+ value <- Map.lookup var $ CF.variablesInScope state+ return $ CF.numericalStatus (CF.variableValue value) >= CF.NumericalStatusMaybe+ _ ->+ case oversimplify t of+ [v] -> all isDigit v+ _ -> False++ isFraction t =+ case oversimplify t of+ [v] -> isJust $ matchRegex floatRegex v+ _ -> False++ eqv ('\\':s) = eqv s+ eqv "<" = "-lt"+ eqv ">" = "-gt"+ eqv "<=" = "-le"+ eqv ">=" = "-ge"+ eqv _ = "the numerical equivalent"++ esc = if typ == SingleBracket then "\\" else ""+ seqv "-ge" = "! a " ++ esc ++ "< b"+ seqv "-gt" = esc ++ ">"+ seqv "-le" = "! a " ++ esc ++ "> b"+ seqv "-lt" = esc ++ "<"+ seqv "-eq" = "="+ seqv "-ne" = "!="+ seqv _ = "the string equivalent"++ invert ('\\':s) = invert s+ invert "<=" = ">"+ invert ">=" = "<"++ floatRegex = mkRegex "^[-+]?[0-9]+\\.[0-9]+$"+checkNumberComparisons _ _ = return ()++prop_checkSingleBracketOperators1 = verify checkSingleBracketOperators "[ test =~ foo ]"+checkSingleBracketOperators params (TC_Binary id SingleBracket "=~" lhs rhs)+ | shellType params `elem` [Bash, Ksh] =+ err id 2074 $ "Can't use =~ in [ ]. Use [[..]] instead."+checkSingleBracketOperators _ _ = return ()++prop_checkDoubleBracketOperators1 = verify checkDoubleBracketOperators "[[ 3 \\< 4 ]]"+prop_checkDoubleBracketOperators3 = verifyNot checkDoubleBracketOperators "[[ foo < bar ]]"+checkDoubleBracketOperators _ x@(TC_Binary id typ op lhs rhs)+ | typ == DoubleBracket && op `elem` ["\\<", "\\>"] =+ err id 2075 $ "Escaping " ++ op ++" is required in [..], but invalid in [[..]]"+checkDoubleBracketOperators _ _ = return ()++prop_checkConditionalAndOrs1 = verify checkConditionalAndOrs "[ foo && bar ]"+prop_checkConditionalAndOrs2 = verify checkConditionalAndOrs "[[ foo -o bar ]]"+prop_checkConditionalAndOrs3 = verifyNot checkConditionalAndOrs "[[ foo || bar ]]"+prop_checkConditionalAndOrs4 = verify checkConditionalAndOrs "[ foo -a bar ]"+prop_checkConditionalAndOrs5 = verify checkConditionalAndOrs "[ -z 3 -o a = b ]"+checkConditionalAndOrs _ t =+ case t of+ (TC_And id SingleBracket "&&" _ _) ->+ err id 2107 "Instead of [ a && b ], use [ a ] && [ b ]."+ (TC_And id DoubleBracket "-a" _ _) ->+ err id 2108 "In [[..]], use && instead of -a."+ (TC_Or id SingleBracket "||" _ _) ->+ err id 2109 "Instead of [ a || b ], use [ a ] || [ b ]."+ (TC_Or id DoubleBracket "-o" _ _) ->+ err id 2110 "In [[..]], use || instead of -o."++ (TC_And id SingleBracket "-a" _ _) ->+ warn id 2166 "Prefer [ p ] && [ q ] as [ p -a q ] is not well defined."+ (TC_Or id SingleBracket "-o" _ _) ->+ warn id 2166 "Prefer [ p ] || [ q ] as [ p -o q ] is not well defined."++ _ -> return ()++prop_checkQuotedCondRegex1 = verify checkQuotedCondRegex "[[ $foo =~ \"bar.*\" ]]"+prop_checkQuotedCondRegex2 = verify checkQuotedCondRegex "[[ $foo =~ '(cow|bar)' ]]"+prop_checkQuotedCondRegex3 = verifyNot checkQuotedCondRegex "[[ $foo =~ $foo ]]"+prop_checkQuotedCondRegex4 = verifyNot checkQuotedCondRegex "[[ $foo =~ \"bar\" ]]"+prop_checkQuotedCondRegex5 = verifyNot checkQuotedCondRegex "[[ $foo =~ 'cow bar' ]]"+prop_checkQuotedCondRegex6 = verify checkQuotedCondRegex "[[ $foo =~ 'cow|bar' ]]"+checkQuotedCondRegex _ (TC_Binary _ _ "=~" _ rhs) =+ case rhs of+ T_NormalWord id [T_DoubleQuoted _ _] -> error rhs+ T_NormalWord id [T_SingleQuoted _ _] -> error rhs+ _ -> return ()+ where+ error t =+ unless (isConstantNonRe t) $+ warn (getId t) 2076+ "Remove quotes from right-hand side of =~ to match as a regex rather than literally."+ re = mkRegex "[][*.+()|]"+ hasMetachars s = s `matches` re+ isConstantNonRe t = fromMaybe False $ do+ s <- getLiteralString t+ return . not $ hasMetachars s+checkQuotedCondRegex _ _ = return ()++prop_checkGlobbedRegex1 = verify checkGlobbedRegex "[[ $foo =~ *foo* ]]"+prop_checkGlobbedRegex2 = verify checkGlobbedRegex "[[ $foo =~ f* ]]"+prop_checkGlobbedRegex3 = verifyNot checkGlobbedRegex "[[ $foo =~ $foo ]]"+prop_checkGlobbedRegex4 = verifyNot checkGlobbedRegex "[[ $foo =~ ^c.* ]]"+prop_checkGlobbedRegex5 = verifyNot checkGlobbedRegex "[[ $foo =~ \\* ]]"+prop_checkGlobbedRegex6 = verifyNot checkGlobbedRegex "[[ $foo =~ (o*) ]]"+prop_checkGlobbedRegex7 = verifyNot checkGlobbedRegex "[[ $foo =~ \\*foo ]]"+prop_checkGlobbedRegex8 = verifyNot checkGlobbedRegex "[[ $foo =~ x\\* ]]"+checkGlobbedRegex _ (TC_Binary _ DoubleBracket "=~" _ rhs)+ | isConfusedGlobRegex s =+ warn (getId rhs) 2049 "=~ is for regex, but this looks like a glob. Use = instead."+ where s = concat $ oversimplify rhs+checkGlobbedRegex _ _ = return ()+++prop_checkConstantIfs1 = verify checkConstantIfs "[[ foo != bar ]]"+prop_checkConstantIfs2a = verify checkConstantIfs "[ n -le 4 ]"+prop_checkConstantIfs2b = verifyNot checkConstantIfs "[[ n -le 4 ]]"+prop_checkConstantIfs3 = verify checkConstantIfs "[[ $n -le 4 && n != 2 ]]"+prop_checkConstantIfs4 = verifyNot checkConstantIfs "[[ $n -le 3 ]]"+prop_checkConstantIfs5 = verifyNot checkConstantIfs "[[ $n -le $n ]]"+prop_checkConstantIfs6 = verifyNot checkConstantIfs "[[ a -ot b ]]"+prop_checkConstantIfs7 = verifyNot checkConstantIfs "[ a -nt b ]"+prop_checkConstantIfs8 = verifyNot checkConstantIfs "[[ ~foo == '~foo' ]]"+prop_checkConstantIfs9 = verify checkConstantIfs "[[ *.png == [a-z] ]]"+prop_checkConstantIfs10 = verifyNot checkConstantIfs "[[ ~me == ~+ ]]"+prop_checkConstantIfs11 = verifyNot checkConstantIfs "[[ ~ == ~+ ]]"+prop_checkConstantIfs12 = verify checkConstantIfs "[[ '~' == x ]]"+checkConstantIfs _ (TC_Binary id typ op lhs rhs) | not isDynamic =+ if isConstant lhs && isConstant rhs+ then warn id 2050 "This expression is constant. Did you forget the $ on a variable?"+ else checkUnmatchable id op lhs rhs+ where+ isDynamic =+ op `elem` arithmeticBinaryTestOps+ && typ == DoubleBracket+ || op `elem` [ "-nt", "-ot", "-ef"]++ checkUnmatchable id op lhs rhs =+ when (op `elem` ["=", "==", "!="] && not (wordsCanBeEqual lhs rhs)) $+ warn id 2193 "The arguments to this comparison can never be equal. Make sure your syntax is correct."+checkConstantIfs _ _ = return ()++prop_checkLiteralBreakingTest = verify checkLiteralBreakingTest "[[ a==$foo ]]"+prop_checkLiteralBreakingTest2 = verify checkLiteralBreakingTest "[ $foo=3 ]"+prop_checkLiteralBreakingTest3 = verify checkLiteralBreakingTest "[ $foo!=3 ]"+prop_checkLiteralBreakingTest4 = verify checkLiteralBreakingTest "[ \"$(ls) \" ]"+prop_checkLiteralBreakingTest5 = verify checkLiteralBreakingTest "[ -n \"$(true) \" ]"+prop_checkLiteralBreakingTest6 = verify checkLiteralBreakingTest "[ -z $(true)z ]"+prop_checkLiteralBreakingTest7 = verifyNot checkLiteralBreakingTest "[ -z $(true) ]"+prop_checkLiteralBreakingTest8 = verifyNot checkLiteralBreakingTest "[ $(true)$(true) ]"+prop_checkLiteralBreakingTest10 = verify checkLiteralBreakingTest "[ -z foo ]"+checkLiteralBreakingTest _ t = sequence_ $+ case t of+ (TC_Nullary _ _ w@(T_NormalWord _ l)) -> do+ guard . not $ isConstant w -- Covered by SC2078+ comparisonWarning l `mplus` tautologyWarning w "Argument to implicit -n is always true due to literal strings."+ (TC_Unary _ _ op w@(T_NormalWord _ l)) ->+ case op of+ "-n" -> tautologyWarning w "Argument to -n is always true due to literal strings."+ "-z" -> tautologyWarning w "Argument to -z is always false due to literal strings."+ _ -> fail "not relevant"+ _ -> fail "not my problem"+ where+ hasEquals = matchToken ('=' `elem`)+ isNonEmpty = matchToken (not . null)+ matchToken m t = maybe False m (getLiteralString t)++ comparisonWarning list = do+ token <- find hasEquals list+ return $ err (getId token) 2077 "You need spaces around the comparison operator."+ tautologyWarning t s = do+ token <- find isNonEmpty $ getWordParts t+ return $ err (getId token) 2157 s++prop_checkConstantNullary = verify checkConstantNullary "[[ '$(foo)' ]]"+prop_checkConstantNullary2 = verify checkConstantNullary "[ \"-f lol\" ]"+prop_checkConstantNullary3 = verify checkConstantNullary "[[ cmd ]]"+prop_checkConstantNullary4 = verify checkConstantNullary "[[ ! cmd ]]"+prop_checkConstantNullary5 = verify checkConstantNullary "[[ true ]]"+prop_checkConstantNullary6 = verify checkConstantNullary "[ 1 ]"+prop_checkConstantNullary7 = verify checkConstantNullary "[ false ]"+checkConstantNullary _ (TC_Nullary _ _ t) | isConstant t =+ case onlyLiteralString t of+ "false" -> err (getId t) 2158 "[ false ] is true. Remove the brackets."+ "0" -> err (getId t) 2159 "[ 0 ] is true. Use 'false' instead."+ "true" -> style (getId t) 2160 "Instead of '[ true ]', just use 'true'."+ "1" -> style (getId t) 2161 "Instead of '[ 1 ]', use 'true'."+ _ -> err (getId t) 2078 "This expression is constant. Did you forget a $ somewhere?"+ where+ string = onlyLiteralString t++checkConstantNullary _ _ = return ()++prop_checkForDecimals1 = verify checkForDecimals "((3.14*c))"+prop_checkForDecimals2 = verify checkForDecimals "foo[1.2]=bar"+prop_checkForDecimals3 = verifyNot checkForDecimals "declare -A foo; foo[1.2]=bar"+checkForDecimals params t@(TA_Expansion id _) = sequence_ $ do+ guard $ not (hasFloatingPoint params)+ first:rest <- getLiteralString t+ guard $ isDigit first && '.' `elem` rest+ return $ err id 2079 "(( )) doesn't support decimals. Use bc or awk."+checkForDecimals _ _ = return ()++prop_checkDivBeforeMult = verify checkDivBeforeMult "echo $((c/n*100))"+prop_checkDivBeforeMult2 = verifyNot checkDivBeforeMult "echo $((c*100/n))"+prop_checkDivBeforeMult3 = verifyNot checkDivBeforeMult "echo $((c/10*10))"+checkDivBeforeMult params (TA_Binary _ "*" (TA_Binary id "/" _ x) y)+ | not (hasFloatingPoint params) && x /= y =+ info id 2017 "Increase precision by replacing a/b*c with a*c/b."+checkDivBeforeMult _ _ = return ()++prop_checkArithmeticDeref = verify checkArithmeticDeref "echo $((3+$foo))"+prop_checkArithmeticDeref2 = verify checkArithmeticDeref "cow=14; (( s+= $cow ))"+prop_checkArithmeticDeref3 = verifyNot checkArithmeticDeref "cow=1/40; (( s+= ${cow%%/*} ))"+prop_checkArithmeticDeref4 = verifyNot checkArithmeticDeref "(( ! $? ))"+prop_checkArithmeticDeref5 = verifyNot checkArithmeticDeref "(($1))"+prop_checkArithmeticDeref6 = verify checkArithmeticDeref "(( a[$i] ))"+prop_checkArithmeticDeref7 = verifyNot checkArithmeticDeref "(( 10#$n ))"+prop_checkArithmeticDeref8 = verifyNot checkArithmeticDeref "let i=$i+1"+prop_checkArithmeticDeref9 = verifyNot checkArithmeticDeref "(( a[foo] ))"+prop_checkArithmeticDeref10 = verifyNot checkArithmeticDeref "(( a[\\$foo] ))"+prop_checkArithmeticDeref11 = verify checkArithmeticDeref "a[$foo]=wee"+prop_checkArithmeticDeref11b = verifyNot checkArithmeticDeref "declare -A a; a[$foo]=wee"+prop_checkArithmeticDeref12 = verify checkArithmeticDeref "for ((i=0; $i < 3; i)); do true; done"+prop_checkArithmeticDeref13 = verifyNot checkArithmeticDeref "(( $$ ))"+prop_checkArithmeticDeref14 = verifyNot checkArithmeticDeref "(( $! ))"+prop_checkArithmeticDeref15 = verifyNot checkArithmeticDeref "(( ${!var} ))"+prop_checkArithmeticDeref16 = verifyNot checkArithmeticDeref "(( ${x+1} + ${x=42} ))"+checkArithmeticDeref params t@(TA_Expansion _ [T_DollarBraced id _ l]) =+ unless (isException $ concat $ oversimplify l) getWarning+ where+ isException [] = True+ isException s@(h:_) = any (`elem` "/.:#%?*@$-!+=^,") s || isDigit h+ getWarning = fromMaybe noWarning . msum . NE.map warningFor $ parents params t+ warningFor t =+ case t of+ T_Arithmetic {} -> return normalWarning+ T_DollarArithmetic {} -> return normalWarning+ T_ForArithmetic {} -> return normalWarning+ T_Assignment {} -> return normalWarning+ T_SimpleCommand {} -> return noWarning+ _ -> Nothing++ normalWarning = style id 2004 "$/${} is unnecessary on arithmetic variables."+ noWarning = return ()+checkArithmeticDeref _ _ = return ()++prop_checkArithmeticBadOctal1 = verify checkArithmeticBadOctal "(( 0192 ))"+prop_checkArithmeticBadOctal2 = verifyNot checkArithmeticBadOctal "(( 0x192 ))"+prop_checkArithmeticBadOctal3 = verifyNot checkArithmeticBadOctal "(( 1 ^ 0777 ))"+checkArithmeticBadOctal _ t@(TA_Expansion id _) = sequence_ $ do+ str <- getLiteralString t+ guard $ str `matches` octalRE+ return $ err id 2080 "Numbers with leading 0 are considered octal."+ where+ octalRE = mkRegex "^0[0-7]*[8-9]"+checkArithmeticBadOctal _ _ = return ()++prop_checkComparisonAgainstGlob = verify checkComparisonAgainstGlob "[[ $cow == $bar ]]"+prop_checkComparisonAgainstGlob2 = verifyNot checkComparisonAgainstGlob "[[ $cow == \"$bar\" ]]"+prop_checkComparisonAgainstGlob3 = verify checkComparisonAgainstGlob "[ $cow = *foo* ]"+prop_checkComparisonAgainstGlob4 = verifyNot checkComparisonAgainstGlob "[ $cow = foo ]"+prop_checkComparisonAgainstGlob5 = verify checkComparisonAgainstGlob "[[ $cow != $bar ]]"+prop_checkComparisonAgainstGlob6 = verify checkComparisonAgainstGlob "[ $f != /* ]"+prop_checkComparisonAgainstGlob7 = verify checkComparisonAgainstGlob "#!/bin/busybox sh\n[[ $f == *foo* ]]"+checkComparisonAgainstGlob _ (TC_Binary _ DoubleBracket op _ (T_NormalWord id [T_DollarBraced _ _ _]))+ | op `elem` ["=", "==", "!="] =+ warn id 2053 $ "Quote the right-hand side of " ++ op ++ " in [[ ]] to prevent glob matching."+checkComparisonAgainstGlob params (TC_Binary _ SingleBracket op _ word)+ | op `elem` ["=", "==", "!="] && isGlob word =+ err (getId word) 2081 msg+ where+ msg = if (shellType params) `elem` [Bash, Ksh] -- Busybox does not support glob matching+ then "[ .. ] can't match globs. Use [[ .. ]] or case statement."+ else "[ .. ] can't match globs. Use a case statement."++checkComparisonAgainstGlob params (TC_Binary _ DoubleBracket op _ word)+ | shellType params == BusyboxSh && op `elem` ["=", "==", "!="] && isGlob word =+ err (getId word) 2330 "BusyBox [[ .. ]] does not support glob matching. Use a case statement."++checkComparisonAgainstGlob _ _ = return ()++prop_checkCaseAgainstGlob1 = verify checkCaseAgainstGlob "case foo in lol$n) foo;; esac"+prop_checkCaseAgainstGlob2 = verify checkCaseAgainstGlob "case foo in $(foo)) foo;; esac"+prop_checkCaseAgainstGlob3 = verifyNot checkCaseAgainstGlob "case foo in *$bar*) foo;; esac"+checkCaseAgainstGlob _ t =+ case t of+ (T_CaseExpression _ _ cases) -> mapM_ check cases+ _ -> return ()+ where+ check (_, list, _) = mapM_ check' list+ check' expr@(T_NormalWord _ list)+ -- If it's already a glob, assume that's what the user wanted+ | not (isGlob expr) && any isQuoteableExpansion list =+ warn (getId expr) 2254 "Quote expansions in case patterns to match literally rather than as a glob."+ check' _ = return ()++prop_checkCommarrays1 = verify checkCommarrays "a=(1, 2)"+prop_checkCommarrays2 = verify checkCommarrays "a+=(1,2,3)"+prop_checkCommarrays3 = verifyNot checkCommarrays "cow=(1 \"foo,bar\" 3)"+prop_checkCommarrays4 = verifyNot checkCommarrays "cow=('one,' 'two')"+prop_checkCommarrays5 = verify checkCommarrays "a=([a]=b, [c]=d)"+prop_checkCommarrays6 = verify checkCommarrays "a=([a]=b,[c]=d,[e]=f)"+prop_checkCommarrays7 = verify checkCommarrays "a=(1,2)"+checkCommarrays _ (T_Array id l) =+ when (any (isCommaSeparated . literal) l) $+ warn id 2054 "Use spaces, not commas, to separate array elements."+ where+ literal (T_IndexedElement _ _ l) = literal l+ literal (T_NormalWord _ l) = concatMap literal l+ literal (T_Literal _ str) = str+ literal _ = ""++ isCommaSeparated = elem ','+checkCommarrays _ _ = return ()++prop_checkOrNeq1 = verify checkOrNeq "if [[ $lol -ne cow || $lol -ne foo ]]; then echo foo; fi"+prop_checkOrNeq2 = verify checkOrNeq "(( a!=lol || a!=foo ))"+prop_checkOrNeq3 = verify checkOrNeq "[ \"$a\" != lol || \"$a\" != foo ]"+prop_checkOrNeq4 = verifyNot checkOrNeq "[ a != $cow || b != $foo ]"+prop_checkOrNeq5 = verifyNot checkOrNeq "[[ $a != /home || $a != */public_html/* ]]"+prop_checkOrNeq6 = verify checkOrNeq "[ $a != a ] || [ $a != b ]"+prop_checkOrNeq7 = verify checkOrNeq "[ $a != a ] || [ $a != b ] || true"+prop_checkOrNeq8 = verifyNot checkOrNeq "[[ $a != x || $a != x ]]"+prop_checkOrNeq9 = verifyNot checkOrNeq "[ 0 -ne $FOO ] || [ 0 -ne $BAR ]"+-- This only catches the most idiomatic cases. Fixme?++-- For test-level "or": [ x != y -o x != z ]+checkOrNeq _ (TC_Or id typ op (TC_Binary _ _ op1 lhs1 rhs1 ) (TC_Binary _ _ op2 lhs2 rhs2))+ | (op1 == op2 && (op1 == "-ne" || op1 == "!=")) && lhs1 == lhs2 && rhs1 /= rhs2 && not (any isGlob [rhs1,rhs2]) =+ warn id 2055 $ "You probably wanted " ++ (if typ == SingleBracket then "-a" else "&&") ++ " here, otherwise it's always true."++-- For arithmetic context "or"+checkOrNeq _ (TA_Binary id "||" (TA_Binary _ "!=" word1 _) (TA_Binary _ "!=" word2 _))+ | word1 == word2 =+ warn id 2056 "You probably wanted && here, otherwise it's always true."++-- For command level "or": [ x != y ] || [ x != z ]+checkOrNeq _ (T_OrIf id lhs rhs) = sequence_ $ do+ (lhs1, op1, rhs1) <- getExpr lhs+ (lhs2, op2, rhs2) <- getExpr rhs+ guard $ op1 == op2 && op1 `elem` ["-ne", "!="]+ guard $ lhs1 == lhs2 && rhs1 /= rhs2+ guard . not $ any isGlob [rhs1, rhs2]+ return $ warn id 2252 "You probably wanted && here, otherwise it's always true."+ where+ getExpr x =+ case x of+ T_OrIf _ lhs _ -> getExpr lhs -- Fetches x and y in `T_OrIf x (T_OrIf y z)`+ T_Pipeline _ _ [x] -> getExpr x+ T_Redirecting _ _ c -> getExpr c+ T_Condition _ _ _ c -> getExpr c+ TC_Binary _ _ op lhs rhs -> orient (lhs, op, rhs)+ _ -> Nothing++ -- Swap items so that the constant side is rhs (or Nothing if both/neither is constant)+ orient (lhs, op, rhs) =+ case (isConstant lhs, isConstant rhs) of+ (True, False) -> return (rhs, op, lhs)+ (False, True) -> return (lhs, op, rhs)+ _ -> Nothing+++checkOrNeq _ _ = return ()+++prop_checkAndEq1 = verifyNot checkAndEq "cow=0; foo=0; if [[ $lol -eq cow && $lol -eq foo ]]; then echo foo; fi"+prop_checkAndEq2 = verifyNot checkAndEq "lol=0 foo=0; (( a==lol && a==foo ))"+prop_checkAndEq3 = verify checkAndEq "[ \"$a\" = lol && \"$a\" = foo ]"+prop_checkAndEq4 = verifyNot checkAndEq "[ a = $cow && b = $foo ]"+prop_checkAndEq5 = verifyNot checkAndEq "[[ $a = /home && $a = */public_html/* ]]"+prop_checkAndEq6 = verify checkAndEq "[ $a = a ] && [ $a = b ]"+prop_checkAndEq7 = verify checkAndEq "[ $a = a ] && [ $a = b ] || true"+prop_checkAndEq8 = verifyNot checkAndEq "[[ $a == x && $a == x ]]"+prop_checkAndEq9 = verifyNot checkAndEq "[ 0 -eq $FOO ] && [ 0 -eq $BAR ]"+prop_checkAndEq10 = verify checkAndEq "(( a == 1 && a == 2 ))"+prop_checkAndEq11 = verify checkAndEq "[ $x -eq 1 ] && [ $x -eq 2 ]"+prop_checkAndEq12 = verify checkAndEq "[ 1 -eq $x ] && [ $x -eq 2 ]"+prop_checkAndEq13 = verifyNot checkAndEq "[ 1 -eq $x ] && [ $x -eq 1 ]"+prop_checkAndEq14 = verifyNot checkAndEq "[ $a = $b ] && [ $a = $c ]"++checkAndEqOperands "-eq" rhs1 rhs2 = isLiteralNumber rhs1 && isLiteralNumber rhs2+checkAndEqOperands op rhs1 rhs2 | op == "=" || op == "==" = isLiteral rhs1 && isLiteral rhs2+checkAndEqOperands _ _ _ = False++-- For test-level "and": [ x = y -a x = z ]+checkAndEq _ (TC_And id typ op (TC_Binary _ _ op1 lhs1 rhs1 ) (TC_Binary _ _ op2 lhs2 rhs2))+ | op1 == op2 && lhs1 == lhs2 && rhs1 /= rhs2 && checkAndEqOperands op1 rhs1 rhs2 =+ warn id 2333 $ "You probably wanted " ++ (if typ == SingleBracket then "-o" else "||") ++ " here, otherwise it's always false."++-- For arithmetic context "and"+checkAndEq _ (TA_Binary id "&&" (TA_Binary _ "==" lhs1 rhs1) (TA_Binary _ "==" lhs2 rhs2))+ | lhs1 == lhs2 && isLiteralNumber rhs1 && isLiteralNumber rhs2 =+ warn id 2334 "You probably wanted || here, otherwise it's always false."++-- For command level "and": [ x = y ] && [ x = z ]+checkAndEq _ (T_AndIf id lhs rhs) = sequence_ $ do+ (lhs1, op1, rhs1) <- getExpr lhs+ (lhs2, op2, rhs2) <- getExpr rhs+ guard $ op1 == op2+ guard $ lhs1 == lhs2 && rhs1 /= rhs2+ guard $ checkAndEqOperands op1 rhs1 rhs2+ return $ warn id 2333 "You probably wanted || here, otherwise it's always false."+ where+ getExpr x =+ case x of+ T_AndIf _ lhs _ -> getExpr lhs -- Fetches x and y in `T_AndIf x (T_AndIf y z)`+ T_Pipeline _ _ [x] -> getExpr x+ T_Redirecting _ _ c -> getExpr c+ T_Condition _ _ _ c -> getExpr c+ TC_Binary _ _ op lhs rhs -> orient (lhs, op, rhs)+ _ -> Nothing++ -- Swap items so that the constant side is rhs (or Nothing if both/neither is constant)+ orient (lhs, op, rhs) =+ case (isConstant lhs, isConstant rhs) of+ (True, False) -> return (rhs, op, lhs)+ (False, True) -> return (lhs, op, rhs)+ _ -> Nothing+++checkAndEq _ _ = return ()+++prop_checkValidCondOps1 = verify checkValidCondOps "[[ a -xz b ]]"+prop_checkValidCondOps2 = verify checkValidCondOps "[ -M a ]"+prop_checkValidCondOps2a = verifyNot checkValidCondOps "[ 3 \\> 2 ]"+prop_checkValidCondOps3 = verifyNot checkValidCondOps "[ 1 = 2 -a 3 -ge 4 ]"+prop_checkValidCondOps4 = verifyNot checkValidCondOps "[[ ! -v foo ]]"+prop_checkValidCondOps5 = verifyNot checkValidCondOps "[ \\! -e foo ]"+prop_checkValidCondOps6 = verifyNot checkValidCondOps "[ '!' -e foo ]"+checkValidCondOps _ (TC_Binary id _ s _ _)+ | s `notElem` binaryTestOps =+ warn id 2057 "Unknown binary operator."+checkValidCondOps _ (TC_Unary id _ s _)+ | s `notElem` unaryTestOps =+ warn id 2058 "Unknown unary operator."+checkValidCondOps _ _ = return ()++prop_checkUuoeVar1 = verify checkUuoeVar "for f in $(echo $tmp); do echo lol; done"+prop_checkUuoeVar2 = verify checkUuoeVar "date +`echo \"$format\"`"+prop_checkUuoeVar3 = verifyNot checkUuoeVar "foo \"$(echo -e '\r')\""+prop_checkUuoeVar4 = verifyNot checkUuoeVar "echo $tmp"+prop_checkUuoeVar5 = verify checkUuoeVar "foo \"$(echo \"$(date) value:\" $value)\""+prop_checkUuoeVar6 = verifyNot checkUuoeVar "foo \"$(echo files: *.png)\""+prop_checkUuoeVar7 = verifyNot checkUuoeVar "foo $(echo $(bar))" -- covered by 2005+prop_checkUuoeVar8 = verifyNot checkUuoeVar "#!/bin/sh\nz=$(echo)"+prop_checkUuoeVar9 = verify checkUuoeVar "foo $(echo $(<file))"+checkUuoeVar _ p =+ case p of+ T_Backticked id [cmd] -> check id cmd+ T_DollarExpansion id [cmd] -> check id cmd+ _ -> return ()+ where+ couldBeOptimized f = case f of+ T_Glob {} -> False+ T_Extglob {} -> False+ T_BraceExpansion {} -> False+ T_NormalWord _ l -> all couldBeOptimized l+ T_DoubleQuoted _ l -> all couldBeOptimized l+ _ -> True++ check id (T_Pipeline _ _ [T_Redirecting _ _ c]) = warnForEcho id c+ check _ _ = return ()+ isCovered first rest = null rest && tokenIsJustCommandOutput first+ warnForEcho id = checkUnqualifiedCommand "echo" $ \_ vars ->+ case vars of+ (first:rest) ->+ unless (isCovered first rest || "-" `isPrefixOf` onlyLiteralString first) $+ when (all couldBeOptimized vars) $ style id 2116+ "Useless echo? Instead of 'cmd $(echo foo)', just use 'cmd foo'."+ _ -> return ()+++prop_checkTestRedirects1 = verify checkTestRedirects "test 3 > 1"+prop_checkTestRedirects2 = verifyNot checkTestRedirects "test 3 \\> 1"+prop_checkTestRedirects3 = verify checkTestRedirects "/usr/bin/test $var > $foo"+prop_checkTestRedirects4 = verifyNot checkTestRedirects "test 1 -eq 2 2> file"+checkTestRedirects _ (T_Redirecting id redirs cmd) | cmd `isCommand` "test" =+ mapM_ check redirs+ where+ check t =+ when (suspicious t) $+ warn (getId t) 2065 "This is interpreted as a shell file redirection, not a comparison."+ suspicious t = -- Ignore redirections of stderr because these are valid for squashing e.g. int errors,+ case t of -- and >> and similar redirections because these are probably not comparisons.+ T_FdRedirect _ fd (T_IoFile _ op _) -> fd /= "2" && isComparison op+ _ -> False+ isComparison t =+ case t of+ T_Greater _ -> True+ T_Less _ -> True+ _ -> False+checkTestRedirects _ _ = return ()++prop_checkPS11 = verify checkPS1Assignments "PS1='\\033[1;35m\\$ '"+prop_checkPS11a = verify checkPS1Assignments "export PS1='\\033[1;35m\\$ '"+prop_checkPSf2 = verify checkPS1Assignments "PS1='\\h \\e[0m\\$ '"+prop_checkPS13 = verify checkPS1Assignments "PS1=$'\\x1b[c '"+prop_checkPS14 = verify checkPS1Assignments "PS1=$'\\e[3m; '"+prop_checkPS14a = verify checkPS1Assignments "export PS1=$'\\e[3m; '"+prop_checkPS15 = verifyNot checkPS1Assignments "PS1='\\[\\033[1;35m\\]\\$ '"+prop_checkPS16 = verifyNot checkPS1Assignments "PS1='\\[\\e1m\\e[1m\\]\\$ '"+prop_checkPS17 = verifyNot checkPS1Assignments "PS1='e033x1B'"+prop_checkPS18 = verifyNot checkPS1Assignments "PS1='\\[\\e\\]'"+checkPS1Assignments _ (T_Assignment _ _ "PS1" _ word) = warnFor word+ where+ warnFor word =+ let contents = concat $ oversimplify word in+ when (containsUnescaped contents) $+ info (getId word) 2025 "Make sure all escape sequences are enclosed in \\[..\\] to prevent line wrapping issues"+ containsUnescaped s =+ let unenclosed = subRegex enclosedRegex s "" in+ isJust $ matchRegex escapeRegex unenclosed+ enclosedRegex = mkRegex "\\\\\\[.*\\\\\\]" -- FIXME: shouldn't be eager+ escapeRegex = mkRegex "\\\\x1[Bb]|\\\\e|\x1B|\\\\033"+checkPS1Assignments _ _ = return ()++prop_checkBackticks1 = verify checkBackticks "echo `foo`"+prop_checkBackticks2 = verifyNot checkBackticks "echo $(foo)"+prop_checkBackticks3 = verifyNot checkBackticks "echo `#inlined comment` foo"+checkBackticks params (T_Backticked id list) | not (null list) =+ addComment $+ makeCommentWithFix StyleC id 2006 "Use $(...) notation instead of legacy backticks `...`."+ (fixWith [replaceStart id params 1 "$(", replaceEnd id params 1 ")"])+checkBackticks _ _ = return ()+++prop_checkBadParameterSubstitution1 = verify checkBadParameterSubstitution "${foo$n}"+prop_checkBadParameterSubstitution2 = verifyNot checkBadParameterSubstitution "${foo//$n/lol}"+prop_checkBadParameterSubstitution3 = verify checkBadParameterSubstitution "${$#}"+prop_checkBadParameterSubstitution4 = verify checkBadParameterSubstitution "${var${n}_$((i%2))}"+prop_checkBadParameterSubstitution5 = verifyNot checkBadParameterSubstitution "${bar}"+prop_checkBadParameterSubstitution6 = verify checkBadParameterSubstitution "${\"bar\"}"+prop_checkBadParameterSubstitution7 = verify checkBadParameterSubstitution "${{var}"+prop_checkBadParameterSubstitution8 = verify checkBadParameterSubstitution "${$(x)//x/y}"+prop_checkBadParameterSubstitution9 = verifyNot checkBadParameterSubstitution "$# ${#} $! ${!} ${!#} ${#!}"+prop_checkBadParameterSubstitution10 = verify checkBadParameterSubstitution "${'foo'}"+prop_checkBadParameterSubstitution11 = verify checkBadParameterSubstitution "${${x%.*}##*/}"++checkBadParameterSubstitution _ t =+ case t of+ (T_DollarBraced i _ (T_NormalWord _ contents@(first:_))) ->+ if isIndirection contents+ then err i 2082 "To expand via indirection, use arrays, ${!name} or (for sh only) eval."+ else checkFirst first+ _ -> return ()++ where++ isIndirection vars =+ let list = mapMaybe isIndirectionPart vars in+ not (null list) && and list++ isIndirectionPart t =+ case t of T_DollarExpansion {} -> Just True+ T_Backticked {} -> Just True+ T_DollarBraced {} -> Just True+ T_DollarArithmetic {} -> Just True+ T_Literal _ s -> if all isVariableChar s+ then Nothing+ else Just False+ _ -> Just False++ checkFirst t =+ case t of+ T_Literal id (c:_) ->+ if isVariableChar c || isSpecialVariableChar c+ then return ()+ else err id 2296 $ "Parameter expansions can't start with " ++ e4m [c] ++ ". Double check syntax."++ T_ParamSubSpecialChar {} -> return ()++ T_DoubleQuoted id [T_Literal _ s] | isVariable s ->+ err id 2297 "Double quotes must be outside ${}: ${\"invalid\"} vs \"${valid}\"."++ T_DollarBraced id braces _ | isUnmodifiedParameterExpansion t ->+ err id 2298 $+ (if braces then "${${x}}" else "${$x}")+ ++ " is invalid. For expansion, use ${x}. For indirection, use arrays, ${!x} or (for sh) eval."++ T_DollarBraced {} ->+ err (getId t) 2299 "Parameter expansions can't be nested. Use temporary variables."++ _ | isCommandSubstitution t ->+ err (getId t) 2300 "Parameter expansion can't be applied to command substitutions. Use temporary variables."++ _ -> err (getId t) 2301 $ "Parameter expansion starts with unexpected " ++ name t ++ ". Double check syntax."++ isVariable str =+ case str of+ [c] -> isVariableStartChar c || isSpecialVariableChar c || isDigit c+ x -> isVariableName x++ name t =+ case t of+ T_SingleQuoted {} -> "quotes"+ T_DoubleQuoted {} -> "quotes"+ _ -> "syntax"+++prop_checkInexplicablyUnquoted1 = verify checkInexplicablyUnquoted "echo 'var='value';'"+prop_checkInexplicablyUnquoted2 = verifyNot checkInexplicablyUnquoted "'foo'*"+prop_checkInexplicablyUnquoted3 = verifyNot checkInexplicablyUnquoted "wget --user-agent='something'"+prop_checkInexplicablyUnquoted4 = verify checkInexplicablyUnquoted "echo \"VALUES (\"id\")\""+prop_checkInexplicablyUnquoted5 = verifyNot checkInexplicablyUnquoted "\"$dir\"/\"$file\""+prop_checkInexplicablyUnquoted6 = verifyNot checkInexplicablyUnquoted "\"$dir\"some_stuff\"$file\""+prop_checkInexplicablyUnquoted7 = verifyNot checkInexplicablyUnquoted "${dir/\"foo\"/\"bar\"}"+prop_checkInexplicablyUnquoted8 = verifyNot checkInexplicablyUnquoted " 'foo'\\\n 'bar'"+prop_checkInexplicablyUnquoted9 = verifyNot checkInexplicablyUnquoted "[[ $x =~ \"foo\"(\"bar\"|\"baz\") ]]"+prop_checkInexplicablyUnquoted10 = verifyNot checkInexplicablyUnquoted "cmd ${x+--name=\"$x\" --output=\"$x.out\"}"+prop_checkInexplicablyUnquoted11 = verifyNot checkInexplicablyUnquoted "echo \"foo\"/\"bar\""+prop_checkInexplicablyUnquoted12 = verifyNot checkInexplicablyUnquoted "declare \"foo\"=\"bar\""+checkInexplicablyUnquoted params (T_NormalWord id tokens) = mapM_ check (tails tokens)+ where+ check (T_SingleQuoted _ _:T_Literal id str:_)+ | not (null str) && all isAlphaNum str =+ info id 2026 "This word is outside of quotes. Did you intend to 'nest '\"'single quotes'\"' instead'? "++ check (T_DoubleQuoted _ a:trapped:T_DoubleQuoted _ b:_) =+ case trapped of+ T_DollarExpansion id _ -> warnAboutExpansion id+ T_DollarBraced id _ _ -> warnAboutExpansion id+ T_Literal id s+ | not (quotesSingleThing a && quotesSingleThing b+ || s `elem` ["=", ":", "/"]+ || isSpecial (NE.toList $ getPath (parentMap params) trapped)+ ) ->+ warnAboutLiteral id+ _ -> return ()++ check _ = return ()++ -- Regexes for [[ .. =~ re ]] are parsed with metacharacters like ()| as unquoted+ -- literals. The same is true for ${x+"foo" "bar"}. Avoid overtriggering on these.+ isSpecial t =+ case t of+ (T_Redirecting {} : _) -> False+ T_DollarBraced {} : _ -> True+ (a:(TC_Binary _ _ "=~" lhs rhs):rest) -> getId a == getId rhs+ _:rest -> isSpecial rest+ _ -> False++ -- If the surrounding quotes quote single things, like "$foo"_and_then_some_"$stuff",+ -- the quotes were probably intentional and harmless.+ quotesSingleThing x = case x of+ [T_DollarExpansion _ _] -> True+ [T_DollarBraced _ _ _] -> True+ [T_Backticked _ _] -> True+ _ -> False++ warnAboutExpansion id =+ warn id 2027 "The surrounding quotes actually unquote this. Remove or escape them."+ warnAboutLiteral id =+ warn id 2140 "Word is of the form \"A\"B\"C\" (B indicated). Did you mean \"ABC\" or \"A\\\"B\\\"C\"?"+checkInexplicablyUnquoted _ _ = return ()++prop_checkTildeInQuotes1 = verify checkTildeInQuotes "var=\"~/out.txt\""+prop_checkTildeInQuotes2 = verify checkTildeInQuotes "foo > '~/dir'"+prop_checkTildeInQuotes4 = verifyNot checkTildeInQuotes "~/file"+prop_checkTildeInQuotes5 = verifyNot checkTildeInQuotes "echo '/~foo/cow'"+prop_checkTildeInQuotes6 = verifyNot checkTildeInQuotes "awk '$0 ~ /foo/'"+checkTildeInQuotes _ = check+ where+ verify id ('~':'/':_) = warn id 2088 "Tilde does not expand in quotes. Use $HOME."+ verify _ _ = return ()+ check (T_NormalWord _ (T_SingleQuoted id str:_)) =+ verify id str+ check (T_NormalWord _ (T_DoubleQuoted _ (T_Literal id str:_):_)) =+ verify id str+ check _ = return ()++prop_checkLonelyDotDash1 = verify checkLonelyDotDash "./ file"+prop_checkLonelyDotDash2 = verifyNot checkLonelyDotDash "./file"+checkLonelyDotDash _ t@(T_Redirecting id _ _)+ | isUnqualifiedCommand t "./" =+ err id 2083 "Don't add spaces after the slash in './file'."+checkLonelyDotDash _ _ = return ()+++prop_checkSpuriousExec1 = verify checkSpuriousExec "exec foo; true"+prop_checkSpuriousExec2 = verify checkSpuriousExec "if a; then exec b; exec c; fi"+prop_checkSpuriousExec3 = verifyNot checkSpuriousExec "echo cow; exec foo"+prop_checkSpuriousExec4 = verifyNot checkSpuriousExec "if a; then exec b; fi"+prop_checkSpuriousExec5 = verifyNot checkSpuriousExec "exec > file; cmd"+prop_checkSpuriousExec6 = verify checkSpuriousExec "exec foo > file; cmd"+prop_checkSpuriousExec7 = verifyNot checkSpuriousExec "exec file; echo failed; exit 3"+prop_checkSpuriousExec8 = verifyNot checkSpuriousExec "exec {origout}>&1- >tmp.log 2>&1; bar"+prop_checkSpuriousExec9 = verify checkSpuriousExec "for file in rc.d/*; do exec \"$file\"; done"+prop_checkSpuriousExec10 = verifyNot checkSpuriousExec "exec file; r=$?; printf >&2 'failed\n'; return $r"+prop_checkSpuriousExec11 = verifyNot checkSpuriousExec "exec file; :"+prop_checkSpuriousExec12 = verifyNot checkSpuriousExec "#!/bin/bash\nshopt -s execfail; exec foo; exec bar; echo 'Error'; exit 1;"+prop_checkSpuriousExec13 = verify checkSpuriousExec "#!/bin/dash\nshopt -s execfail; exec foo; exec bar; echo 'Error'; exit 1;"+checkSpuriousExec params t = when (not $ hasExecfail params) $ doLists t+ where+ doLists (T_Script _ _ cmds) = doList cmds False+ doLists (T_BraceGroup _ cmds) = doList cmds False+ doLists (T_WhileExpression _ _ cmds) = doList cmds True+ doLists (T_UntilExpression _ _ cmds) = doList cmds True+ doLists (T_ForIn _ _ _ cmds) = doList cmds True+ doLists (T_ForArithmetic _ _ _ _ cmds) = doList cmds True+ doLists (T_IfExpression _ thens elses) = do+ mapM_ (\(_, l) -> doList l False) thens+ doList elses False+ doLists _ = return ()++ stripCleanup = reverse . dropWhile cleanup . reverse+ cleanup (T_Pipeline _ _ [cmd]) =+ isCommandMatch cmd (`elem` [":", "echo", "exit", "printf", "return"])+ || isAssignment cmd+ cleanup _ = False++ doList = doList' . stripCleanup+ -- The second parameter is True if we are in a loop+ -- In that case we should emit the warning also if `exec' is the last statement+ doList' (current:t@(following:_)) False = do+ commentIfExec current+ doList t False+ doList' (current:tail) True = do+ commentIfExec current+ doList tail True+ doList' _ _ = return ()++ commentIfExec (T_Pipeline id _ [c]) = commentIfExec c+ commentIfExec (T_Redirecting _ _ (T_SimpleCommand id _ (cmd:additionalArg:_))) |+ getLiteralString cmd == Just "exec" =+ warn id 2093 "Remove \"exec \" if script should continue after this command."+ commentIfExec _ = return ()+++prop_checkSpuriousExpansion1 = verify checkSpuriousExpansion "if $(true); then true; fi"+prop_checkSpuriousExpansion3 = verifyNot checkSpuriousExpansion "$(cmd) --flag1 --flag2"+prop_checkSpuriousExpansion4 = verify checkSpuriousExpansion "$((i++))"+checkSpuriousExpansion _ (T_SimpleCommand _ _ [T_NormalWord _ [word]]) = check word+ where+ check word = case word of+ T_DollarExpansion id _ ->+ warn id 2091 "Remove surrounding $() to avoid executing output (or use eval if intentional)."+ T_Backticked id _ ->+ warn id 2092 "Remove backticks to avoid executing output (or use eval if intentional)."+ T_DollarArithmetic id _ ->+ err id 2084 "Remove '$' or use '_=$((expr))' to avoid executing output."+ _ -> return ()+checkSpuriousExpansion _ _ = return ()+++prop_checkDollarBrackets1 = verify checkDollarBrackets "echo $[1+2]"+prop_checkDollarBrackets2 = verifyNot checkDollarBrackets "echo $((1+2))"+checkDollarBrackets _ (T_DollarBracket id _) =+ style id 2007 "Use $((..)) instead of deprecated $[..]"+checkDollarBrackets _ _ = return ()++prop_checkSshHereDoc1 = verify checkSshHereDoc "ssh host << foo\necho $PATH\nfoo"+prop_checkSshHereDoc2 = verifyNot checkSshHereDoc "ssh host << 'foo'\necho $PATH\nfoo"+checkSshHereDoc _ (T_Redirecting _ redirs cmd)+ | cmd `isCommand` "ssh" =+ mapM_ checkHereDoc redirs+ where+ hasVariables = mkRegex "[`$]"+ checkHereDoc (T_FdRedirect _ _ (T_HereDoc id _ Unquoted token tokens))+ | not (all isConstant tokens) =+ warn id 2087 $ "Quote '" ++ (e4m token) ++ "' to make here document expansions happen on the server side rather than on the client."+ checkHereDoc _ = return ()+checkSshHereDoc _ _ = return ()++--- Subshell detection+prop_subshellAssignmentCheck = verifyTree subshellAssignmentCheck "cat foo | while read bar; do a=$bar; done; echo \"$a\""+prop_subshellAssignmentCheck2 = verifyNotTree subshellAssignmentCheck "while read bar; do a=$bar; done < file; echo \"$a\""+prop_subshellAssignmentCheck3 = verifyTree subshellAssignmentCheck "( A=foo; ); rm $A"+prop_subshellAssignmentCheck4 = verifyNotTree subshellAssignmentCheck "( A=foo; rm $A; )"+prop_subshellAssignmentCheck5 = verifyTree subshellAssignmentCheck "cat foo | while read cow; do true; done; echo $cow;"+prop_subshellAssignmentCheck6 = verifyTree subshellAssignmentCheck "( export lol=$(ls); ); echo $lol;"+prop_subshellAssignmentCheck6a = verifyTree subshellAssignmentCheck "( typeset -a lol=a; ); echo $lol;"+prop_subshellAssignmentCheck7 = verifyTree subshellAssignmentCheck "cmd | while read foo; do (( n++ )); done; echo \"$n lines\""+prop_subshellAssignmentCheck8 = verifyTree subshellAssignmentCheck "n=3 & echo $((n++))"+prop_subshellAssignmentCheck9 = verifyTree subshellAssignmentCheck "read n & n=foo$n"+prop_subshellAssignmentCheck10 = verifyTree subshellAssignmentCheck "(( n <<= 3 )) & (( n |= 4 )) &"+prop_subshellAssignmentCheck11 = verifyTree subshellAssignmentCheck "cat /etc/passwd | while read line; do let n=n+1; done\necho $n"+prop_subshellAssignmentCheck12 = verifyTree subshellAssignmentCheck "cat /etc/passwd | while read line; do let ++n; done\necho $n"+prop_subshellAssignmentCheck13 = verifyTree subshellAssignmentCheck "#!/bin/bash\necho foo | read bar; echo $bar"+prop_subshellAssignmentCheck14 = verifyNotTree subshellAssignmentCheck "#!/bin/ksh93\necho foo | read bar; echo $bar"+prop_subshellAssignmentCheck15 = verifyNotTree subshellAssignmentCheck "#!/bin/ksh\ncat foo | while read bar; do a=$bar; done\necho \"$a\""+prop_subshellAssignmentCheck16 = verifyNotTree subshellAssignmentCheck "(set -e); echo $@"+prop_subshellAssignmentCheck17 = verifyNotTree subshellAssignmentCheck "foo=${ { bar=$(baz); } 2>&1; }; echo $foo $bar"+prop_subshellAssignmentCheck18 = verifyTree subshellAssignmentCheck "( exec {n}>&2; ); echo $n"+prop_subshellAssignmentCheck19 = verifyNotTree subshellAssignmentCheck "#!/bin/bash\nshopt -s lastpipe; echo a | read -r b; echo \"$b\""+prop_subshellAssignmentCheck20 = verifyTree subshellAssignmentCheck "@test 'foo' { a=1; }\n@test 'bar' { echo $a; }\n"+prop_subshellAssignmentCheck21 = verifyNotTree subshellAssignmentCheck "test1() { echo foo | if [[ $var ]]; then echo $var; fi; }; test2() { echo $var; }"+prop_subshellAssignmentCheck22 = verifyNotTree subshellAssignmentCheck "( [[ -n $foo || -z $bar ]] ); echo $foo $bar"+prop_subshellAssignmentCheck23 = verifyNotTree subshellAssignmentCheck "( export foo ); echo $foo"+prop_subshellAssignmentCheck24 = verifyNotTree subshellAssignmentCheck "( read -r a _ c <<< 'x y z'; ); echo $_"+prop_subshellAssignmentCheck25 = verifyNotTree subshellAssignmentCheck "( _=discard; ); echo $_"+prop_subshellAssignmentCheck26 = verifyNotTree subshellAssignmentCheck "( a=1; ); f() { echo $a; }"+prop_subshellAssignmentCheck27 = verifyNotTree subshellAssignmentCheck "#!/usr/bin/env bats\n@test 'foo' { run true; [ \"$status\" -eq 0 ]; }\nf() { run true; [ \"$status\" -eq 0 ]; }\n@test 'bar' { f; }"+prop_subshellAssignmentCheck28 = verifyTree subshellAssignmentCheck "f() { ( a=1; ); }; echo $a"+prop_subshellAssignmentCheck29 = verifyTree subshellAssignmentCheck "f() { ( a=1; ); echo $a; }"+prop_subshellAssignmentCheck30 = verifyNotTree subshellAssignmentCheck "( f() { a=1; }; ); echo $a"+prop_subshellAssignmentCheck31 = verifyNotTree subshellAssignmentCheck "#!/usr/bin/env bats\n@test 'foo' { export a=1; }\n@test 'bar' { export a=2; }"+prop_subshellAssignmentCheck32 = verifyNotTree subshellAssignmentCheck "( a=1; ); declare -x a=2; echo $a"+prop_subshellAssignmentCheck33 = verifyTree subshellAssignmentCheck "( a=1; ); export a+=2"+prop_subshellAssignmentCheck34 = verifyTree subshellAssignmentCheck "f() { cmd | while read x; do n=1; done; }; f; echo $n"+prop_subshellAssignmentCheck35 = verifyNotTree subshellAssignmentCheck "#!/usr/bin/env bats\n@test 'foo' { f() { a=1; }; }\n@test 'bar' { f; echo $a; }"+prop_subshellAssignmentCheck40 = verifyNotTree subshellAssignmentCheck "#!/usr/bin/env bats\n@test 'foo' { ( run true; ) & run true; echo $status; }"+prop_subshellAssignmentCheck41 = verifyTree subshellAssignmentCheck "( run true; ); echo $status"+prop_subshellAssignmentCheck42 = verifyNotTree subshellAssignmentCheck "#!/usr/bin/env bats\n@test 'foo' { run true | cat; }\n@test 'bar' { true; }"+subshellAssignmentCheck params t =+ let flow = variableFlow params+ check = findSubshelled flow [(InSubshell "oops",[])] Map.empty+ in execWriter check++data SubshellCheckScope =+ InSubshell String -- The reason for the subshell+ | InFunction (Map.Map String VariableState) -- Variable states outside the function+++findSubshelled [] _ _ = return ()+findSubshelled (Assignment x@(_, _, str, data_):rest) scopes@((kind,scope):restscope) deadVars =+ if isTrueAssignmentSource data_+ then findSubshelled rest ((kind, x:scope):restscope) $ Map.insert str Alive deadVars+ else findSubshelled rest scopes deadVars++findSubshelled (Reference (_, readToken, str):rest) scopes deadVars = do+ unless (shouldIgnore str || isAssignedBy readToken) $ case Map.findWithDefault Alive str deadVars of+ Alive -> return ()+ Dead writeToken reason -> do+ info (getId writeToken) 2030 $ "Modification of " ++ str ++ " is local (to subshell caused by "++ reason ++")."+ info (getId readToken) 2031 $ str ++ " was modified in a subshell. That change might be lost."+ findSubshelled rest scopes deadVars+ where+ shouldIgnore str =+ str `elem` ["@", "*", "_", "IFS"]+ -- `export foo=bar` references foo, but does not read its old value+ isAssignedBy (T_Assignment _ Assign name _ _) = name == str+ isAssignedBy _ = False++findSubshelled (StackScope (SubshellScope reason):rest) scopes deadVars =+ findSubshelled rest ((InSubshell reason,[]):scopes) deadVars++-- A function body runs where the function is called, not where it is defined,+-- so subshells preceding the definition don't affect the variables it reads.+findSubshelled (StackScope FunctionScope:rest) scopes deadVars =+ findSubshelled rest ((InFunction deadVars,[]):scopes) Map.empty++findSubshelled (StackScopeEnd:rest) ((InSubshell reason, scope):oldScopes) deadVars =+ findSubshelled rest oldScopes $+ foldl (\m (_, token, var, _) ->+ Map.insert var (Dead token reason) m) deadVars scope++-- Likewise, assignments in a function body are not made where the function is+-- defined, so don't add them to the enclosing scope. Keep the effects of+-- subshells inside the function though.+findSubshelled (StackScopeEnd:rest) ((InFunction outerVars, _):oldScopes) deadVars =+ findSubshelled rest oldScopes $ Map.union deadVars outerVars+++-- FIXME: This is a very strange way of doing it.+-- For each variable read/write, run a stateful function that emits+-- comments. The comments are collected and returned.+doVariableFlowAnalysis ::+ (Token -> Token -> String -> State t [v])+ -> (Token -> Token -> String -> DataType -> State t [v])+ -> t+ -> [StackData]+ -> [v]++doVariableFlowAnalysis readFunc writeFunc empty flow = evalState (+ foldM (\list x -> do { l <- doFlow x; return $ l ++ list; }) [] flow+ ) empty+ where+ doFlow (Reference (base, token, name)) =+ readFunc base token name+ doFlow (Assignment (base, token, name, values)) =+ writeFunc base token name values+ doFlow _ = return []++-- Don't suggest quotes if this will instead be autocorrected+-- from $foo=bar to foo=bar. This is not pretty but ok.+quotesMayConflictWithSC2281 params t =+ case getPath (parentMap params) t of+ _ NE.:| T_NormalWord parentId (me:T_Literal _ ('=':_):_) : T_SimpleCommand _ _ (cmd:_) : _ ->+ (getId t) == (getId me) && (parentId == getId cmd)+ _ -> False++addDoubleQuotesAround params token = (surroundWith (getId token) params "\"")++prop_checkSpacefulnessCfg1 = verify checkSpacefulnessCfg "a='cow moo'; echo $a"+prop_checkSpacefulnessCfg2 = verifyNot checkSpacefulnessCfg "a='cow moo'; [[ $a ]]"+prop_checkSpacefulnessCfg3 = verifyNot checkSpacefulnessCfg "a='cow*.mp3'; echo \"$a\""+prop_checkSpacefulnessCfg4 = verify checkSpacefulnessCfg "for f in *.mp3; do echo $f; done"+prop_checkSpacefulnessCfg4a = verifyNot checkSpacefulnessCfg "foo=3; foo=$(echo $foo)"+prop_checkSpacefulnessCfg5 = verify checkSpacefulnessCfg "a='*'; b=$a; c=lol${b//foo/bar}; echo $c"+prop_checkSpacefulnessCfg6 = verify checkSpacefulnessCfg "a=foo$(lol); echo $a"+prop_checkSpacefulnessCfg7 = verify checkSpacefulnessCfg "a=foo\\ bar; rm $a"+prop_checkSpacefulnessCfg8 = verifyNot checkSpacefulnessCfg "a=foo\\ bar; a=foo; rm $a"+prop_checkSpacefulnessCfg10 = verify checkSpacefulnessCfg "rm $1"+prop_checkSpacefulnessCfg11 = verify checkSpacefulnessCfg "rm ${10//foo/bar}"+prop_checkSpacefulnessCfg12 = verifyNot checkSpacefulnessCfg "(( $1 + 3 ))"+prop_checkSpacefulnessCfg13 = verifyNot checkSpacefulnessCfg "if [[ $2 -gt 14 ]]; then true; fi"+prop_checkSpacefulnessCfg14 = verifyNot checkSpacefulnessCfg "foo=$3 env"+prop_checkSpacefulnessCfg15 = verifyNot checkSpacefulnessCfg "local foo=$1"+prop_checkSpacefulnessCfg16 = verifyNot checkSpacefulnessCfg "declare foo=$1"+prop_checkSpacefulnessCfg17 = verify checkSpacefulnessCfg "echo foo=$1"+prop_checkSpacefulnessCfg18 = verifyNot checkSpacefulnessCfg "$1 --flags"+prop_checkSpacefulnessCfg19 = verify checkSpacefulnessCfg "echo $PWD"+prop_checkSpacefulnessCfg20 = verifyNot checkSpacefulnessCfg "n+='foo bar'"+prop_checkSpacefulnessCfg21 = verifyNot checkSpacefulnessCfg "select foo in $bar; do true; done"+prop_checkSpacefulnessCfg22 = verifyNot checkSpacefulnessCfg "echo $\"$1\""+prop_checkSpacefulnessCfg23 = verifyNot checkSpacefulnessCfg "a=(1); echo ${a[@]}"+prop_checkSpacefulnessCfg24 = verify checkSpacefulnessCfg "a='a b'; cat <<< $a"+prop_checkSpacefulnessCfg25 = verify checkSpacefulnessCfg "a='s/[0-9]//g'; sed $a"+prop_checkSpacefulnessCfg26 = verify checkSpacefulnessCfg "a='foo bar'; echo {1,2,$a}"+prop_checkSpacefulnessCfg27 = verifyNot checkSpacefulnessCfg "echo ${a:+'foo'}"+prop_checkSpacefulnessCfg28 = verifyNot checkSpacefulnessCfg "exec {n}>&1; echo $n"+prop_checkSpacefulnessCfg29 = verifyNot checkSpacefulnessCfg "n=$(stuff); exec {n}>&-;"+prop_checkSpacefulnessCfg30 = verify checkSpacefulnessCfg "file='foo bar'; echo foo > $file;"+prop_checkSpacefulnessCfg31 = verifyNot checkSpacefulnessCfg "echo \"`echo \\\"$1\\\"`\""+prop_checkSpacefulnessCfg32 = verifyNot checkSpacefulnessCfg "var=$1; [ -v var ]"+prop_checkSpacefulnessCfg33 = verify checkSpacefulnessCfg "for file; do echo $file; done"+prop_checkSpacefulnessCfg34 = verify checkSpacefulnessCfg "declare foo$n=$1"+prop_checkSpacefulnessCfg35 = verifyNot checkSpacefulnessCfg "echo ${1+\"$1\"}"+prop_checkSpacefulnessCfg36 = verifyNot checkSpacefulnessCfg "arg=$#; echo $arg"+prop_checkSpacefulnessCfg37 = verifyNot checkSpacefulnessCfg "@test 'status' {\n [ $status -eq 0 ]\n}"+prop_checkSpacefulnessCfg37v = verify checkVerboseSpacefulnessCfg "@test 'status' {\n [ $status -eq 0 ]\n}"+prop_checkSpacefulnessCfg38 = verify checkSpacefulnessCfg "a=; echo $a"+prop_checkSpacefulnessCfg39 = verifyNot checkSpacefulnessCfg "a=''\"\"''; b=x$a; echo $b"+prop_checkSpacefulnessCfg40 = verifyNot checkSpacefulnessCfg "a=$((x+1)); echo $a"+prop_checkSpacefulnessCfg41 = verifyNot checkSpacefulnessCfg "exec $1 --flags"+prop_checkSpacefulnessCfg42 = verifyNot checkSpacefulnessCfg "run $1 --flags"+prop_checkSpacefulnessCfg43 = verifyNot checkSpacefulnessCfg "$foo=42"+prop_checkSpacefulnessCfg44 = verify checkSpacefulnessCfg "#!/bin/sh\nexport var=$value"+prop_checkSpacefulnessCfg45 = verifyNot checkSpacefulnessCfg "wait -zzx -p foo; echo $foo"+prop_checkSpacefulnessCfg46 = verifyNot checkSpacefulnessCfg "x=0; (( x += 1 )); echo $x"+prop_checkSpacefulnessCfg47 = verifyNot checkSpacefulnessCfg "x=0; (( x-- )); echo $x"+prop_checkSpacefulnessCfg48 = verifyNot checkSpacefulnessCfg "x=0; (( ++x )); echo $x"+prop_checkSpacefulnessCfg49 = verifyNot checkSpacefulnessCfg "for i in 1 2 3; do echo $i; done"+prop_checkSpacefulnessCfg50 = verify checkSpacefulnessCfg "for i in 1 2 *; do echo $i; done"+prop_checkSpacefulnessCfg51 = verify checkSpacefulnessCfg "x='foo bar'; x && x=1; echo $x"+prop_checkSpacefulnessCfg52 = verifyNot checkSpacefulnessCfg "x=1; if f; then x='foo bar'; exit; fi; echo $x"+prop_checkSpacefulnessCfg53 = verifyNot checkSpacefulnessCfg "s=1; f() { local s='a b'; }; f; echo $s"+prop_checkSpacefulnessCfg54 = verifyNot checkSpacefulnessCfg "s='a b'; f() { s=1; }; f; echo $s"+prop_checkSpacefulnessCfg55 = verify checkSpacefulnessCfg "s='a b'; x && f() { s=1; }; f; echo $s"+prop_checkSpacefulnessCfg56 = verifyNot checkSpacefulnessCfg "s=1; cat <(s='a b'); echo $s"+prop_checkSpacefulnessCfg57 = verifyNot checkSpacefulnessCfg "declare -i s=0; s=$(f); echo $s"+prop_checkSpacefulnessCfg58 = verify checkSpacefulnessCfg "f() { declare -i s; }; f; s=$(var); echo $s"+prop_checkSpacefulnessCfg59 = verifyNot checkSpacefulnessCfg "f() { declare -gi s; }; f; s=$(var); echo $s"+prop_checkSpacefulnessCfg60 = verify checkSpacefulnessCfg "declare -i s; declare +i s; s=$(foo); echo $s"+prop_checkSpacefulnessCfg61 = verify checkSpacefulnessCfg "declare -x X; y=foo$X; echo $y;"+prop_checkSpacefulnessCfg62 = verifyNot checkSpacefulnessCfg "f() { declare -x X; y=foo$X; echo $y; }"+prop_checkSpacefulnessCfg63 = verify checkSpacefulnessCfg "f && declare -i s; s='x + y'; echo $s"+prop_checkSpacefulnessCfg64 = verifyNot checkSpacefulnessCfg "declare -i s; s='x + y'; x=$s; echo $x"+prop_checkSpacefulnessCfg65 = verifyNot checkSpacefulnessCfg "f() { s=$?; echo $s; }; f"+prop_checkSpacefulnessCfg66 = verifyNot checkSpacefulnessCfg "f() { s=$?; echo $s; }"++checkSpacefulnessCfg = checkSpacefulnessCfg' True+checkVerboseSpacefulnessCfg = checkSpacefulnessCfg' False++checkSpacefulnessCfg' :: Bool -> (Parameters -> Token -> Writer [TokenComment] ())+checkSpacefulnessCfg' dirtyPass params token@(T_DollarBraced id _ list) =+ when (needsQuoting && (dirtyPass == not isClean)) $+ unless (name `elem` specialVariablesWithoutSpaces || quotesMayConflictWithSC2281 params token) $+ if dirtyPass+ then+ if isDefaultAssignment (parentMap params) token+ then+ info (getId token) 2223+ "This default assignment may cause DoS due to globbing. Quote it."+ else+ infoWithFix id 2086 "Double quote to prevent globbing and word splitting." $+ addDoubleQuotesAround params token+ else+ styleWithFix id 2248 "Prefer double quoting even when variables don't contain special characters." $+ addDoubleQuotesAround params token++ where+ bracedString = concat $ oversimplify list+ name = getBracedReference bracedString+ parents = parentMap params+ needsQuoting =+ not (isArrayExpansion token) -- There's another warning for this+ && not (isCountingReference token)+ && not (isQuoteFree (shellType params) parents token)+ && not (isQuotedAlternativeReference token)+ && not (usedAsCommandName parents token)++ isClean = fromMaybe False $ do+ cfga <- cfgAnalysis params+ state <- CF.getIncomingState cfga id+ value <- Map.lookup name $ CF.variablesInScope state+ return $ isCleanState value++ isCleanState state =+ (all (S.member CFVPInteger) $ CF.variableProperties state)+ || CF.spaceStatus (CF.variableValue state) == CF.SpaceStatusClean++ isDefaultAssignment parents token =+ let modifier = getBracedModifier bracedString in+ any (`isPrefixOf` modifier) ["=", ":="]+ && isParamTo parents ":" token++checkSpacefulnessCfg' _ _ _ = return ()+++prop_CheckVariableBraces1 = verify checkVariableBraces "a='123'; echo $a"+prop_CheckVariableBraces2 = verifyNot checkVariableBraces "a='123'; echo ${a}"+prop_CheckVariableBraces3 = verifyNot checkVariableBraces "#shellcheck disable=SC2016\necho '$a'"+prop_CheckVariableBraces4 = verifyNot checkVariableBraces "echo $* $1"+prop_CheckVariableBraces5 = verifyNot checkVariableBraces "$foo=42"+checkVariableBraces params t@(T_DollarBraced id False l)+ | name `notElem` unbracedVariables && not (quotesMayConflictWithSC2281 params t) =+ styleWithFix id 2250+ "Prefer putting braces around variable references even when not strictly required."+ (fixFor t)+ where+ name = getBracedReference $ concat $ oversimplify l+ fixFor token = fixWith [replaceStart (getId token) params 1 "${"+ ,replaceEnd (getId token) params 0 "}"]+checkVariableBraces _ _ = return ()++prop_checkQuotesInLiterals1 = verifyTree checkQuotesInLiterals "param='--foo=\"bar\"'; app $param"+prop_checkQuotesInLiterals1a = verifyTree checkQuotesInLiterals "param=\"--foo='lolbar'\"; app $param"+prop_checkQuotesInLiterals2 = verifyNotTree checkQuotesInLiterals "param='--foo=\"bar\"'; app \"$param\""+prop_checkQuotesInLiterals3 =verifyNotTree checkQuotesInLiterals "param=('--foo='); app \"${param[@]}\""+prop_checkQuotesInLiterals4 = verifyNotTree checkQuotesInLiterals "param=\"don't bother with this one\"; app $param"+prop_checkQuotesInLiterals5 = verifyNotTree checkQuotesInLiterals "param=\"--foo='lolbar'\"; eval app $param"+prop_checkQuotesInLiterals6 = verifyTree checkQuotesInLiterals "param='my\\ file'; cmd=\"rm $param\"; $cmd"+prop_checkQuotesInLiterals6a = verifyNotTree checkQuotesInLiterals "param='my\\ file'; cmd=\"rm ${#param}\"; $cmd"+prop_checkQuotesInLiterals7 = verifyTree checkQuotesInLiterals "param='my\\ file'; rm $param"+prop_checkQuotesInLiterals8 = verifyTree checkQuotesInLiterals "param=\"/foo/'bar baz'/etc\"; rm $param"+prop_checkQuotesInLiterals9 = verifyNotTree checkQuotesInLiterals "param=\"/foo/'bar baz'/etc\"; rm ${#param}"+checkQuotesInLiterals params t =+ doVariableFlowAnalysis readF writeF Map.empty (variableFlow params)+ where+ getQuotes name = gets (Map.lookup name)+ setQuotes name ref = modify $ Map.insert name ref+ deleteQuotes = modify . Map.delete+ parents = parentMap params+ quoteRegex = mkRegex "\"|([/= ]|^)'|'( |$)|\\\\ "+ containsQuotes s = s `matches` quoteRegex++ writeF _ _ name (DataString (SourceFrom values)) = do+ quoteMap <- get+ let quotedVars = msum $ map (forToken quoteMap) values+ case quotedVars of+ Nothing -> deleteQuotes name+ Just x -> setQuotes name x+ return []+ writeF _ _ _ _ = return []++ forToken map (T_DollarBraced id _ t) =+ -- skip getBracedReference here to avoid false positives on PE+ Map.lookup (concat . oversimplify $ t) map+ forToken quoteMap (T_DoubleQuoted id tokens) =+ msum $ map (forToken quoteMap) tokens+ forToken quoteMap (T_NormalWord id tokens) =+ msum $ map (forToken quoteMap) tokens+ forToken _ t =+ if containsQuotes (concat $ oversimplify t)+ then return $ getId t+ else Nothing++ squashesQuotes t =+ case t of+ T_DollarBraced id _ l -> "#" `isPrefixOf` concat (oversimplify l)+ _ -> False++ readF _ expr name = do+ assignment <- getQuotes name+ return $ case assignment of+ Just j+ | not (isParamTo parents "eval" expr)+ && not (isQuoteFree (shellType params) parents expr)+ && not (squashesQuotes expr)+ -> [+ makeComment WarningC j 2089 $+ "Quotes/backslashes will be treated literally. " ++ suggestion,+ makeComment WarningC (getId expr) 2090+ "Quotes/backslashes in this variable will not be respected."+ ]+ _ -> []+ suggestion =+ if supportsArrays (shellType params)+ then "Use an array."+ else "Rewrite using set/\"$@\" or functions."+++prop_checkFunctionsUsedExternally1 =+ verifyTree checkFunctionsUsedExternally "foo() { :; }; sudo foo"+prop_checkFunctionsUsedExternally2 =+ verifyTree checkFunctionsUsedExternally "alias f='a'; xargs -0 f"+prop_checkFunctionsUsedExternally2b =+ verifyNotTree checkFunctionsUsedExternally "alias f='a'; find . -type f"+prop_checkFunctionsUsedExternally2c =+ verifyTree checkFunctionsUsedExternally "alias f='a'; find . -type f -exec f {} +"+prop_checkFunctionsUsedExternally3 =+ verifyNotTree checkFunctionsUsedExternally "f() { :; }; echo f"+prop_checkFunctionsUsedExternally4 =+ verifyNotTree checkFunctionsUsedExternally "foo() { :; }; run0 \"foo\""+prop_checkFunctionsUsedExternally5 =+ verifyTree checkFunctionsUsedExternally "foo() { :; }; ssh host foo"+prop_checkFunctionsUsedExternally6 =+ verifyNotTree checkFunctionsUsedExternally "foo() { :; }; ssh host echo foo"+prop_checkFunctionsUsedExternally7 =+ verifyNotTree checkFunctionsUsedExternally "install() { :; }; sudo apt-get install foo"+prop_checkFunctionsUsedExternally8 =+ verifyTree checkFunctionsUsedExternally "foo() { :; }; command sudo foo"+prop_checkFunctionsUsedExternally9 =+ verifyTree checkFunctionsUsedExternally "foo() { :; }; exec -c doas foo"+prop_checkFunctionsUsedExternally10 =+ verifyTree checkFunctionsUsedExternally "foo() { :; }; timeout -p 10 foo"+checkFunctionsUsedExternally params t =+ runNodeAnalysis checkCommand params t+ where+ checkCommand _ t@(T_SimpleCommand _ _ argv) =+ case getCommandNameAndToken False t of+ (Just str, t) -> do+ let name = basename str+ let args = skipOver t argv+ let argStrings = map (\x -> (onlyLiteralString x, x)) args+ let candidates = getPotentialCommands name argStrings+ mapM_ (checkArg name (getId t)) candidates+ _ -> return ()+ checkCommand _ _ = return ()++ skipOver t list = drop 1 $ dropWhile (\c -> getId c /= id) $ list+ where id = getId t++ -- Try to pick out the argument[s] that may be commands+ getPotentialCommands name argAndString =+ case name of+ "chroot" -> firstNonFlag+ "screen" -> firstNonFlag+ "sudo" -> firstNonFlag+ "doas" -> firstNonFlag+ "run0" -> firstNonFlag+ "xargs" -> firstNonFlag+ "tmux" -> firstNonFlag+ "timeout" -> take 1 $ drop 1 $ dropFlags argAndString+ "ssh" -> take 1 $ drop 1 $ dropFlags argAndString+ "find" -> take 1 $ drop 1 $+ dropWhile (\x -> fst x `notElem` findExecFlags) argAndString+ _ -> []+ where+ firstNonFlag = take 1 $ dropFlags argAndString+ findExecFlags = ["-exec", "-execdir", "-ok", "-okdir"]+ dropFlags = dropWhile (\x -> "-" `isPrefixOf` fst x)++ functionsAndAliases = Map.union (functions t) (aliases t)++ patternContext id =+ case posLine . fst <$> Map.lookup id (tokenPositions params) of+ Just l -> " on line " <> show l <> "."+ _ -> "."++ checkArg cmd cmdId (_, arg) = sequence_ $ do+ literalArg <- getUnquotedLiteral arg -- only consider unquoted literals+ definitionId <- Map.lookup literalArg functionsAndAliases+ return $ do+ warn (getId arg) 2033+ "Shell functions can't be passed to external commands. Use separate script or sh -c."+ info definitionId 2032 $+ "This function can't be invoked via " ++ cmd ++ patternContext cmdId++prop_checkUnused0 = verifyNotTree checkUnusedAssignments "var=foo; echo $var"+prop_checkUnused1 = verifyTree checkUnusedAssignments "var=foo; echo $bar"+prop_checkUnused2 = verifyNotTree checkUnusedAssignments "var=foo; export var;"+prop_checkUnused3 = verifyTree checkUnusedAssignments "for f in *; do echo '$f'; done"+prop_checkUnused4 = verifyTree checkUnusedAssignments "local i=0"+prop_checkUnused5 = verifyNotTree checkUnusedAssignments "read lol; echo $lol"+prop_checkUnused6 = verifyNotTree checkUnusedAssignments "var=4; (( var++ ))"+prop_checkUnused7 = verifyNotTree checkUnusedAssignments "var=2; $((var))"+prop_checkUnused8 = verifyTree checkUnusedAssignments "var=2; var=3;"+prop_checkUnused9 = verifyNotTree checkUnusedAssignments "read ''"+prop_checkUnused10 = verifyNotTree checkUnusedAssignments "read -p 'test: '"+prop_checkUnused11 = verifyNotTree checkUnusedAssignments "bar=5; export foo[$bar]=3"+prop_checkUnused12 = verifyNotTree checkUnusedAssignments "read foo; echo ${!foo}"+prop_checkUnused13 = verifyNotTree checkUnusedAssignments "x=(1); (( x[0] ))"+prop_checkUnused14 = verifyNotTree checkUnusedAssignments "x=(1); n=0; echo ${x[n]}"+prop_checkUnused15 = verifyNotTree checkUnusedAssignments "x=(1); n=0; (( x[n] ))"+prop_checkUnused16 = verifyNotTree checkUnusedAssignments "foo=5; declare -x foo"+prop_checkUnused16b = verifyNotTree checkUnusedAssignments "f() { local -x foo; foo=42; bar; }; f"+prop_checkUnused17 = verifyNotTree checkUnusedAssignments "read -i 'foo' -e -p 'Input: ' bar; $bar;"+prop_checkUnused18 = verifyNotTree checkUnusedAssignments "a=1; arr=( [$a]=42 ); echo \"${arr[@]}\""+prop_checkUnused19 = verifyNotTree checkUnusedAssignments "a=1; let b=a+1; echo $b"+prop_checkUnused20 = verifyNotTree checkUnusedAssignments "a=1; PS1='$a'"+prop_checkUnused21 = verifyNotTree checkUnusedAssignments "a=1; trap 'echo $a' INT"+prop_checkUnused22 = verifyNotTree checkUnusedAssignments "a=1; [ -v a ]"+prop_checkUnused23 = verifyNotTree checkUnusedAssignments "a=1; [ -R a ]"+prop_checkUnused24 = verifyNotTree checkUnusedAssignments "mapfile -C a b; echo ${b[@]}"+prop_checkUnused25 = verifyNotTree checkUnusedAssignments "readarray foo; echo ${foo[@]}"+prop_checkUnused26 = verifyNotTree checkUnusedAssignments "declare -F foo"+prop_checkUnused27 = verifyTree checkUnusedAssignments "var=3; [ var -eq 3 ]"+prop_checkUnused28 = verifyNotTree checkUnusedAssignments "var=3; [[ var -eq 3 ]]"+prop_checkUnused29 = verifyNotTree checkUnusedAssignments "var=(a b); declare -p var"+prop_checkUnused30 = verifyTree checkUnusedAssignments "let a=1"+prop_checkUnused31 = verifyTree checkUnusedAssignments "let 'a=1'"+prop_checkUnused32 = verifyTree checkUnusedAssignments "let a=b=c; echo $a"+prop_checkUnused33 = verifyNotTree checkUnusedAssignments "a=foo; [[ foo =~ ^{$a}$ ]]"+prop_checkUnused34 = verifyNotTree checkUnusedAssignments "foo=1; (( t = foo )); echo $t"+prop_checkUnused35 = verifyNotTree checkUnusedAssignments "a=foo; b=2; echo ${a:b}"+prop_checkUnused36 = verifyNotTree checkUnusedAssignments "if [[ -v foo ]]; then true; fi"+prop_checkUnused37 = verifyNotTree checkUnusedAssignments "fd=2; exec {fd}>&-"+prop_checkUnused38 = verifyTree checkUnusedAssignments "(( a=42 ))"+prop_checkUnused39 = verifyNotTree checkUnusedAssignments "declare -x -f foo"+prop_checkUnused40 = verifyNotTree checkUnusedAssignments "arr=(1 2); num=2; echo \"${arr[@]:num}\""+prop_checkUnused41 = verifyNotTree checkUnusedAssignments "@test 'foo' {\ntrue\n}\n"+prop_checkUnused42 = verifyNotTree checkUnusedAssignments "DEFINE_string foo '' ''; echo \"${FLAGS_foo}\""+prop_checkUnused43 = verifyTree checkUnusedAssignments "DEFINE_string foo '' ''"+prop_checkUnused44 = verifyNotTree checkUnusedAssignments "DEFINE_string \"foo$ibar\" x y"+prop_checkUnused45 = verifyTree checkUnusedAssignments "readonly foo=bar"+prop_checkUnused46 = verifyTree checkUnusedAssignments "readonly foo=(bar)"+prop_checkUnused47 = verifyNotTree checkUnusedAssignments "a=1; alias hello='echo $a'"+prop_checkUnused48 = verifyNotTree checkUnusedAssignments "_a=1"+prop_checkUnused49 = verifyNotTree checkUnusedAssignments "declare -A array; key=a; [[ -v array[$key] ]]"+prop_checkUnused50 = verifyNotTree checkUnusedAssignments "foofunc() { :; }; typeset -fx foofunc"+prop_checkUnused51 = verifyTree checkUnusedAssignments "x[y[z=1]]=1; echo ${x[@]}"+prop_checkUnused52 = verifyNotTree checkUnusedAssignments "set -o allexport\nfoo=bar"+prop_checkUnused53 = verifyNotTree checkUnusedAssignments "run --separate-stderr true"+prop_checkUnused54 = verifyNotTree checkUnusedAssignments "#!/usr/bin/env bats\n@test 'foo' { true; }"+prop_checkUnused55 = verifyTree checkUnusedAssignments "run=1"+prop_checkUnused56 = verifyNotTree checkUnusedAssignments "run foo bar"+prop_checkUnused57 = verifyTree checkUnusedAssignments "#!/usr/bin/env bats\n@test 'foo' { output=$(true); }"++checkUnusedAssignments params t = execWriter (mapM_ warnFor unused)+ where+ flow = variableFlow params+ references = Map.union (Map.fromList [(stripSuffix name, ()) | Reference (base, token, name) <- flow]) defaultMap++ assignments = Map.fromList [(name, token) | Assignment (base, token, name, _) <- flow, isVariableName name, not $ isBats base]+ -- Variables set by bats' run (or pretended to be set by @test)+ -- are for the caller to check, if needed+ isBats t = case t of+ T_SimpleCommand _ _ (cmd:_) -> getLiteralString cmd == Just "run"+ T_BatsTest {} -> True+ _ -> False++ unused = Map.assocs $ Map.difference assignments references++ warnFor (name, token) =+ unless ("_" `isPrefixOf` name || hasAllexport params) $+ warn (getId token) 2034 $+ name ++ " appears unused. Verify use (or export if used externally)."++ stripSuffix = takeWhile isVariableChar+ defaultMap = Map.fromList $ zip internalVariables $ repeat ()++prop_checkUnassignedReferences1 = verifyTree checkUnassignedReferences "echo $foo"+prop_checkUnassignedReferences2 = verifyNotTree checkUnassignedReferences "foo=hello; echo $foo"+prop_checkUnassignedReferences3 = verifyTree checkUnassignedReferences "MY_VALUE=3; echo $MYVALUE"+prop_checkUnassignedReferences4 = verifyNotTree checkUnassignedReferences "RANDOM2=foo; echo $RANDOM"+prop_checkUnassignedReferences5 = verifyNotTree checkUnassignedReferences "declare -A foo=([bar]=baz); echo ${foo[bar]}"+prop_checkUnassignedReferences6 = verifyNotTree checkUnassignedReferences "foo=..; echo ${foo-bar}"+prop_checkUnassignedReferences7 = verifyNotTree checkUnassignedReferences "getopts ':h' foo; echo $foo"+prop_checkUnassignedReferences8 = verifyNotTree checkUnassignedReferences "let 'foo = 1'; echo $foo"+prop_checkUnassignedReferences9 = verifyNotTree checkUnassignedReferences "echo ${foo-bar}"+prop_checkUnassignedReferences10 = verifyNotTree checkUnassignedReferences "echo ${foo:?}"+prop_checkUnassignedReferences11 = verifyNotTree checkUnassignedReferences "declare -A foo; echo \"${foo[@]}\""+prop_checkUnassignedReferences12 = verifyNotTree checkUnassignedReferences "typeset -a foo; echo \"${foo[@]}\""+prop_checkUnassignedReferences13 = verifyNotTree checkUnassignedReferences "f() { local foo; echo $foo; }"+prop_checkUnassignedReferences14 = verifyNotTree checkUnassignedReferences "foo=; echo $foo"+prop_checkUnassignedReferences15 = verifyNotTree checkUnassignedReferences "f() { true; }; export -f f"+prop_checkUnassignedReferences16 = verifyNotTree checkUnassignedReferences "declare -A foo=( [a b]=bar ); echo ${foo[a b]}"+prop_checkUnassignedReferences17 = verifyNotTree checkUnassignedReferences "USERS=foo; echo $USER"+prop_checkUnassignedReferences18 = verifyNotTree checkUnassignedReferences "FOOBAR=42; export FOOBAR="+prop_checkUnassignedReferences19 = verifyNotTree checkUnassignedReferences "readonly foo=bar; echo $foo"+prop_checkUnassignedReferences20 = verifyNotTree checkUnassignedReferences "printf -v foo bar; echo $foo"+prop_checkUnassignedReferences21 = verifyTree checkUnassignedReferences "echo ${#foo}"+prop_checkUnassignedReferences22 = verifyNotTree checkUnassignedReferences "echo ${!os*}"+prop_checkUnassignedReferences23 = verifyTree checkUnassignedReferences "declare -a foo; foo[bar]=42;"+prop_checkUnassignedReferences24 = verifyNotTree checkUnassignedReferences "declare -A foo; foo[bar]=42;"+prop_checkUnassignedReferences25 = verifyNotTree checkUnassignedReferences "declare -A foo=(); foo[bar]=42;"+prop_checkUnassignedReferences26 = verifyNotTree checkUnassignedReferences "a::b() { foo; }; readonly -f a::b"+prop_checkUnassignedReferences27 = verifyNotTree checkUnassignedReferences ": ${foo:=bar}"+prop_checkUnassignedReferences28 = verifyNotTree checkUnassignedReferences "#!/bin/ksh\necho \"${.sh.version}\"\n"+prop_checkUnassignedReferences29 = verifyNotTree checkUnassignedReferences "if [[ -v foo ]]; then echo $foo; fi"+prop_checkUnassignedReferences30 = verifyNotTree checkUnassignedReferences "if [[ -v foo[3] ]]; then echo ${foo[3]}; fi"+prop_checkUnassignedReferences31 = verifyNotTree checkUnassignedReferences "X=1; if [[ -v foo[$X+42] ]]; then echo ${foo[$X+42]}; fi"+prop_checkUnassignedReferences32 = verifyNotTree checkUnassignedReferences "if [[ -v \"foo[1]\" ]]; then echo ${foo[@]}; fi"+prop_checkUnassignedReferences33 = verifyNotTree checkUnassignedReferences "f() { local -A foo; echo \"${foo[@]}\"; }"+prop_checkUnassignedReferences34 = verifyNotTree checkUnassignedReferences "declare -A foo; (( foo[bar] ))"+prop_checkUnassignedReferences35 = verifyNotTree checkUnassignedReferences "echo ${arr[foo-bar]:?fail}"+prop_checkUnassignedReferences36 = verifyNotTree checkUnassignedReferences "read -a foo -r <<<\"foo bar\"; echo \"$foo\""+prop_checkUnassignedReferences37 = verifyNotTree checkUnassignedReferences "var=howdy; printf -v 'array[0]' %s \"$var\"; printf %s \"${array[0]}\";"+prop_checkUnassignedReferences38 = verifyTree (checkUnassignedReferences' True) "echo $VAR"+prop_checkUnassignedReferences39 = verifyNotTree checkUnassignedReferences "builtin export var=4; echo $var"+prop_checkUnassignedReferences40 = verifyNotTree checkUnassignedReferences ": ${foo=bar}"+prop_checkUnassignedReferences41 = verifyNotTree checkUnassignedReferences "mapfile -t files 123; echo \"${files[@]}\""+prop_checkUnassignedReferences42 = verifyNotTree checkUnassignedReferences "mapfile files -t; echo \"${files[@]}\""+prop_checkUnassignedReferences43 = verifyNotTree checkUnassignedReferences "mapfile --future files; echo \"${files[@]}\""+prop_checkUnassignedReferences_minusNPlain = verifyNotTree checkUnassignedReferences "if [ -n \"$x\" ]; then echo $x; fi"+prop_checkUnassignedReferences_minusZPlain = verifyNotTree checkUnassignedReferences "if [ -z \"$x\" ]; then echo \"\"; fi"+prop_checkUnassignedReferences_minusNBraced = verifyNotTree checkUnassignedReferences "if [ -n \"${x}\" ]; then echo $x; fi"+prop_checkUnassignedReferences_minusZBraced = verifyNotTree checkUnassignedReferences "if [ -z \"${x}\" ]; then echo \"\"; fi"+prop_checkUnassignedReferences_minusNDefault = verifyNotTree checkUnassignedReferences "if [ -n \"${x:-}\" ]; then echo $x; fi"+prop_checkUnassignedReferences_minusZDefault = verifyNotTree checkUnassignedReferences "if [ -z \"${x:-}\" ]; then echo \"\"; fi"+prop_checkUnassignedReferences50 = verifyNotTree checkUnassignedReferences "echo ${foo:+bar}"+prop_checkUnassignedReferences51 = verifyNotTree checkUnassignedReferences "echo ${foo:+$foo}"+prop_checkUnassignedReferences52 = verifyNotTree checkUnassignedReferences "wait -p pid; echo $pid"+prop_checkUnassignedReferences53 = verifyTree checkUnassignedReferences "x=($foo)"+prop_checkUnassignedReferences54 = verifyNotTree checkUnassignedReferences "f() { run true; echo \"$status $output ${lines[0]}\"; }"+prop_checkUnassignedReferences55 = verifyNotTree checkUnassignedReferences "#!/usr/bin/env bats\n@test 'foo' { run_wrapper; echo \"$status $stderr\"; }"+prop_checkUnassignedReferences56 = verifyTree checkUnassignedReferences "f() { run true; echo $stderr; }"+prop_checkUnassignedReferences57 = verifyNotTree checkUnassignedReferences "f() { run -1 --separate-stderr false; echo \"$stderr ${stderr_lines[0]}\"; }"+prop_checkUnassignedReferences58 = verifyTree checkUnassignedReferences "echo $stderr"+prop_checkUnassignedReferences59 = verifyNotTree checkUnassignedReferences "compgen -V files -G '*'; echo \"${files[@]}\""+prop_checkUnassignedReferences60 = verifyNotTree checkUnassignedReferences "compgen -A function -V funcs; echo \"${funcs[@]}\""++checkUnassignedReferences = checkUnassignedReferences' False+checkUnassignedReferences' includeGlobals params t = warnings+ where+ (readMap, writeMap) = execState (mapM tally $ variableFlow params) (Map.empty, Map.empty)+ defaultAssigned = Map.fromList $ map (\a -> (a, ())) $ filter (not . null) internalVariables++ tally (Assignment (_, _, name, _)) =+ modify (\(read, written) -> (read, Map.insert name () written))+ tally (Reference (_, place, name)) =+ modify (\(read, written) -> (Map.insertWith (const id) name place read, written))+ tally _ = return ()++ unassigned = Map.toList $ Map.difference (Map.difference readMap writeMap) defaultAssigned+ writtenVars = filter isVariableName $ Map.keys writeMap++ getBestMatch var = do+ (match, score) <- listToMaybe best+ guard $ goodMatch var match score+ return match+ where+ matches = map (\x -> (x, match var x)) writtenVars+ best = sortBy (comparing snd) matches+ goodMatch var match score =+ let l = length match in+ l > 3 && score <= 1+ || l > 7 && score <= 2++ isLocal = any isLower++ warningForGlobals var place = do+ match <- getBestMatch var+ return $ info (getId place) 2153 $+ "Possible misspelling: " ++ var ++ " may not be assigned. Did you mean " ++ match ++ "?"++ warningForLocals var place =+ return $ warn (getId place) 2154 $+ var ++ " is referenced but not assigned" ++ optionalTip ++ "."+ where+ optionalTip =+ if var `elem` commonCommands+ then " (for output from commands, use \"$(" ++ var ++ " ..." ++ ")\" )"+ else fromMaybe "" $ do+ match <- getBestMatch var+ return $ " (did you mean '" ++ match ++ "'?)"++ warningFor (var, place) = do+ guard $ isVariableName var+ guard . not $ isException var place || isGuarded place+ (if includeGlobals || isLocal var+ then warningForLocals+ else warningForGlobals) var place++ warnings = execWriter . sequence $ mapMaybe warningFor unassigned++ -- ${foo[bar baz]} may not be referencing bar/baz. Just skip these.+ -- We can also have ${foo:+$foo} should be treated like [[ -n $foo ]] && echo $foo+ isException var t = any shouldExclude $ getPath (parentMap params) t+ where+ shouldExclude t =+ case t of+ (T_DollarBraced _ _ l) ->+ let str = concat $ oversimplify l+ ref = getBracedReference str+ mod = getBracedModifier str+ in+ -- Either we're used as an array index like ${arr[here]}+ ref /= var ||+ -- or the reference is guarded by a parent, ${here:+foo$here}+ "+" `isPrefixOf` mod || ":+" `isPrefixOf` mod+ _ -> False++ isGuarded (T_DollarBraced _ _ v) =+ rest `matches` guardRegex+ where+ name = concat $ oversimplify v+ rest = dropWhile isVariableChar $ dropWhile (`elem` "#!") name+ isGuarded _ = False+ -- :? or :- with optional array index and colon+ guardRegex = mkRegex "^(\\[.*\\])?:?[-?]"++ match var candidate =+ if var /= candidate && map toLower var == map toLower candidate+ then 1+ else dist var candidate+++prop_checkGlobsAsOptions1 = verify checkGlobsAsOptions "rm *.txt"+prop_checkGlobsAsOptions2 = verify checkGlobsAsOptions "ls ??.*"+prop_checkGlobsAsOptions3 = verifyNot checkGlobsAsOptions "rm -- *.txt"+prop_checkGlobsAsOptions4 = verifyNot checkGlobsAsOptions "*.txt"+prop_checkGlobsAsOptions5 = verifyNot checkGlobsAsOptions "echo 'Files:' *.txt"+prop_checkGlobsAsOptions6 = verifyNot checkGlobsAsOptions "printf '%s\\n' *"+prop_checkGlobsAsOptions7 = verifyNot checkGlobsAsOptions "set -f; ls *"+prop_checkGlobsAsOptions8 = verifyNot checkGlobsAsOptions "set -o noglob\nrm *"+checkGlobsAsOptions params cmd@(T_SimpleCommand _ _ args) =+ unless (((fromMaybe "" $ getCommandBasename cmd) `elem` ["echo", "printf"]) || hasNoglob params) $+ mapM_ check $ takeWhile (not . isEndOfArgs) (drop 1 args)+ where+ check v@(T_NormalWord _ (T_Glob id s:_)) | s == "*" || s == "?" =+ info id 2035 "Use ./*glob* or -- *glob* so names with dashes won't become options."+ check _ = return ()++ isEndOfArgs t =+ case concat $ oversimplify t of+ "--" -> True+ ":::" -> True+ "::::" -> True+ _ -> False++checkGlobsAsOptions _ _ = return ()+++prop_checkWhileReadPitfalls1 = verify checkWhileReadPitfalls "while read foo; do ssh $foo uptime; done < file"+prop_checkWhileReadPitfalls2 = verifyNot checkWhileReadPitfalls "while read -u 3 foo; do ssh $foo uptime; done 3< file"+prop_checkWhileReadPitfalls3 = verifyNot checkWhileReadPitfalls "while true; do ssh host uptime; done"+prop_checkWhileReadPitfalls4 = verifyNot checkWhileReadPitfalls "while read foo; do ssh $foo hostname < /dev/null; done"+prop_checkWhileReadPitfalls5 = verifyNot checkWhileReadPitfalls "while read foo; do echo ls | ssh $foo; done"+prop_checkWhileReadPitfalls6 = verifyNot checkWhileReadPitfalls "while read foo <&3; do ssh $foo; done 3< foo"+prop_checkWhileReadPitfalls7 = verify checkWhileReadPitfalls "while read foo; do if true; then ssh $foo uptime; fi; done < file"+prop_checkWhileReadPitfalls8 = verifyNot checkWhileReadPitfalls "while read foo; do ssh -n $foo uptime; done < file"+prop_checkWhileReadPitfalls9 = verify checkWhileReadPitfalls "while read foo; do ffmpeg -i foo.mkv bar.mkv -an; done"+prop_checkWhileReadPitfalls10 = verify checkWhileReadPitfalls "while read foo; do mplayer foo.ogv > file; done"+prop_checkWhileReadPitfalls11 = verifyNot checkWhileReadPitfalls "while read foo; do mplayer foo.ogv <<< q; done"+prop_checkWhileReadPitfalls12 = verifyNot checkWhileReadPitfalls "while read foo\ndo\nmplayer foo.ogv << EOF\nq\nEOF\ndone"+prop_checkWhileReadPitfalls13 = verify checkWhileReadPitfalls "while read foo; do x=$(ssh host cmd); done"+prop_checkWhileReadPitfalls14 = verify checkWhileReadPitfalls "while read foo; do echo $(ssh host cmd) < /dev/null; done"+prop_checkWhileReadPitfalls15 = verify checkWhileReadPitfalls "while read foo; do ssh $foo cmd & done"++checkWhileReadPitfalls params (T_WhileExpression id [command] contents)+ | isStdinReadCommand command =+ mapM_ checkMuncher contents+ where+ -- Map of munching commands to a function that checks if the flags should exclude it+ munchers = Map.fromList [+ ("ssh", (hasFlag, addFlag, "-n")),+ ("ffmpeg", (hasArgument, addFlag, "-nostdin")),+ ("mplayer", (hasArgument, addFlag, "-noconsolecontrols")),+ ("HandBrakeCLI", (\_ _ -> False, addRedirect, "< /dev/null"))+ ]+ -- Use flag parsing, e.g. "-an" -> "a", "n"+ hasFlag ('-':flag) = elem flag . map snd . getAllFlags+ -- Simple string match, e.g. "-an" -> "-an"+ hasArgument arg = elem arg . mapMaybe getLiteralString . fromJust . getCommandArgv+ addFlag string cmd = fixWith [replaceEnd (getId $ getCommandTokenOrThis cmd) params 0 (' ':string)]+ addRedirect string cmd = fixWith [replaceEnd (getId cmd) params 0 (' ':string)]++ isStdinReadCommand (T_Pipeline _ _ [T_Redirecting id redirs cmd]) =+ let plaintext = oversimplify cmd+ in headOrDefault "" plaintext == "read"+ && ("-u" `notElem` plaintext)+ && not (any stdinRedirect redirs)+ isStdinReadCommand _ = False++ checkMuncher :: Token -> Writer [TokenComment] ()+ checkMuncher (T_Pipeline _ _ (T_Redirecting _ redirs cmd:_)) = do+ -- Check command substitutions regardless of the command+ case cmd of+ T_SimpleCommand _ vars args ->+ mapM_ checkMuncher $ concat $ concatMap getCommandSequences $ concatMap getWords $ vars ++ args+ _ -> return ()++ unless (any stdinRedirect redirs) $ do+ -- Recurse into ifs/loops/groups/etc if this doesn't redirect+ mapM_ checkMuncher $ concat $ getCommandSequences cmd++ -- Check the actual command+ sequence_ $ do+ name <- getCommandBasename cmd+ (check, fix, flag) <- Map.lookup name munchers+ guard $ not (check flag cmd)++ return $ do+ info id 2095 $+ name ++ " may swallow stdin, preventing this loop from working properly."+ warnWithFix (getId cmd) 2095+ ("Use " ++ name ++ " " ++ flag ++ " to prevent " ++ name ++ " from swallowing stdin.")+ (fix flag cmd)+ checkMuncher (T_Backgrounded _ t) = checkMuncher t+ checkMuncher _ = return ()++ stdinRedirect (T_FdRedirect _ fd op)+ | fd == "0" = True+ | fd == "" =+ case op of+ T_IoFile _ (T_Less _) _ -> True+ T_IoDuplicate _ (T_LESSAND _) _ -> True+ T_HereString _ _ -> True+ T_HereDoc {} -> True+ _ -> False+ stdinRedirect _ = False++ getWords t =+ case t of+ T_Assignment _ _ _ _ x -> getWordParts x+ _ -> getWordParts t+checkWhileReadPitfalls _ _ = return ()+++prop_checkPrefixAssign1 = verify checkPrefixAssignmentReference "var=foo echo $var"+prop_checkPrefixAssign2 = verifyNot checkPrefixAssignmentReference "var=$(echo $var) cmd"+checkPrefixAssignmentReference params t@(T_DollarBraced id _ value) =+ check path+ where+ name = getBracedReference $ concat $ oversimplify value+ path = NE.toList $ getPath (parentMap params) t+ idPath = map getId path++ check [] = return ()+ check (t:rest) =+ case t of+ T_SimpleCommand _ vars (_:_) -> mapM_ checkVar vars+ _ -> check rest+ checkVar (T_Assignment aId mode aName [] value) |+ aName == name && (aId `notElem` idPath) = do+ warn aId 2097 "This assignment is only seen by the forked process."+ warn id 2098 "This expansion will not see the mentioned assignment."+ checkVar _ = return ()++checkPrefixAssignmentReference _ _ = return ()++prop_checkCharRangeGlob1 = verify checkCharRangeGlob "ls *[:digit:].jpg"+prop_checkCharRangeGlob2 = verifyNot checkCharRangeGlob "ls *[[:digit:]].jpg"+prop_checkCharRangeGlob3 = verify checkCharRangeGlob "ls [10-15]"+prop_checkCharRangeGlob4 = verifyNot checkCharRangeGlob "ls [a-zA-Z]"+prop_checkCharRangeGlob5 = verifyNot checkCharRangeGlob "tr -d [aa]" -- tr has 2060+prop_checkCharRangeGlob6 = verifyNot checkCharRangeGlob "[[ $x == [!!]* ]]"+prop_checkCharRangeGlob7 = verifyNot checkCharRangeGlob "[[ -v arr[keykey] ]]"+prop_checkCharRangeGlob8 = verifyNot checkCharRangeGlob "[[ arr[keykey] -gt 1 ]]"+prop_checkCharRangeGlob9 = verifyNot checkCharRangeGlob "read arr[keykey]" -- tr has 2313+checkCharRangeGlob p t@(T_Glob id str) |+ isCharClass str && not isIgnoredCommand && not (isDereferenced t) =+ if ":" `isPrefixOf` contents+ && ":" `isSuffixOf` contents+ && contents /= ":"+ then warn id 2101 "Named class needs outer [], e.g. [[:digit:]]."+ else+ when ('[' `notElem` contents && hasDupes) $+ info id 2102 "Ranges can only match single chars (mentioned due to duplicates)."+ where+ isCharClass str = "[" `isPrefixOf` str && "]" `isSuffixOf` str+ contents = dropNegation . drop 1 . take (length str - 1) $ str+ hasDupes = any ((>1) . length) . group . sort . filter (/= '-') $ contents+ dropNegation s =+ case s of+ '!':rest -> rest+ '^':rest -> rest+ x -> x++ isIgnoredCommand = fromMaybe False $ do+ cmd <- getClosestCommand (parentMap p) t+ return $ isCommandMatch cmd (`elem` ["tr", "read"])++ -- Check if this is a dereferencing context like [[ -v array[operandhere] ]]+ isDereferenced = fromMaybe False . msum . NE.map isDereferencingOp . getPath (parentMap p)+ isDereferencingOp t =+ case t of+ TC_Binary _ DoubleBracket str _ _ -> return $ isDereferencingBinaryOp str+ TC_Unary _ _ str _ -> return $ str == "-v"+ T_SimpleCommand {} -> return False+ _ -> Nothing+checkCharRangeGlob _ _ = return ()++++prop_checkCdAndBack1 = verify checkCdAndBack "for f in *; do cd $f; git pull; cd ..; done"+prop_checkCdAndBack2 = verifyNot checkCdAndBack "for f in *; do cd $f || continue; git pull; cd ..; done"+prop_checkCdAndBack3 = verifyNot checkCdAndBack "while [[ $PWD != / ]]; do cd ..; done"+prop_checkCdAndBack4 = verify checkCdAndBack "cd $tmp; foo; cd -"+prop_checkCdAndBack5 = verifyNot checkCdAndBack "cd ..; foo; cd .."+prop_checkCdAndBack6 = verify checkCdAndBack "for dir in */; do cd \"$dir\"; some_cmd; cd ..; done"+prop_checkCdAndBack7 = verifyNot checkCdAndBack "set -e; for dir in */; do cd \"$dir\"; some_cmd; cd ..; done"+prop_checkCdAndBack8 = verifyNot checkCdAndBack "cd tmp\nfoo\n# shellcheck disable=SC2103\ncd ..\n"+checkCdAndBack params t =+ unless (hasErrexit params) $ mapM_ doList $ getCommandSequences t+ where+ isCdRevert t =+ case oversimplify t of+ [_, p] -> p `elem` ["..", "-"]+ _ -> False++ getCandidate (T_Annotation _ _ x) = getCandidate x+ getCandidate (T_Pipeline id _ [x]) | x `isCommand` "cd" = return x+ getCandidate _ = Nothing++ findCdPair list =+ case list of+ (a:b:rest) ->+ if isCdRevert b && not (isCdRevert a)+ then return $ getId b+ else findCdPair (b:rest)+ _ -> Nothing++ doList list = sequence_ $ do+ cd <- findCdPair $ mapMaybe getCandidate list+ return $ info cd 2103 "Use a ( subshell ) to avoid having to cd back."++prop_checkLoopKeywordScope1 = verify checkLoopKeywordScope "continue 2"+prop_checkLoopKeywordScope2 = verify checkLoopKeywordScope "for f; do ( break; ); done"+prop_checkLoopKeywordScope3 = verify checkLoopKeywordScope "if true; then continue; fi"+prop_checkLoopKeywordScope4 = verifyNot checkLoopKeywordScope "while true; do break; done"+prop_checkLoopKeywordScope5 = verify checkLoopKeywordScope "if true; then break; fi"+prop_checkLoopKeywordScope6 = verify checkLoopKeywordScope "while true; do true | { break; }; done"+prop_checkLoopKeywordScope7 = verifyNot checkLoopKeywordScope "#!/bin/ksh\nwhile true; do true | { break; }; done"+checkLoopKeywordScope params t |+ Just name <- getCommandName t, name `elem` ["continue", "break"] =+ if any isLoop path+ then case map subshellType $ filter (not . isFunction) path of+ Just str:_ -> warn (getId t) 2106 $+ "This only exits the subshell caused by the " ++ str ++ "."+ _ -> return ()+ else case path of+ -- breaking at a source/function invocation is an abomination. Let's ignore it.+ h:_ | isFunction h -> err (getId t) 2104 $ "In functions, use return instead of " ++ name ++ "."+ _ -> err (getId t) 2105 $ name ++ " is only valid in loops."+ where+ path = let p = getPath (parentMap params) t in NE.filter relevant p+ subshellType t = case leadType params t of+ SubshellScope str -> return str+ _ -> Nothing+ relevant t = isLoop t || isFunction t || isJust (subshellType t)+checkLoopKeywordScope _ _ = return ()+++prop_checkFunctionDeclarations1 = verify checkFunctionDeclarations "#!/bin/ksh\nfunction foo() { command foo --lol \"$@\"; }"+prop_checkFunctionDeclarations2 = verify checkFunctionDeclarations "#!/bin/dash\nfunction foo { lol; }"+prop_checkFunctionDeclarations3 = verifyNot checkFunctionDeclarations "foo() { echo bar; }"+checkFunctionDeclarations params+ (T_Function id (FunctionKeyword hasKeyword) (FunctionParentheses hasParens) _ _) =+ case shellType params of+ Bash -> return ()+ Ksh ->+ when (hasKeyword && hasParens) $+ err id 2111 "ksh does not allow 'function' keyword and '()' at the same time."+ Dash -> forSh+ BusyboxSh -> forSh+ Sh -> forSh++ where+ forSh = do+ when (hasKeyword && hasParens) $+ warn id 2112 "'function' keyword is non-standard. Delete it."+ when (hasKeyword && not hasParens) $+ warn id 2113 "'function' keyword is non-standard. Use 'foo()' instead of 'function foo'."+checkFunctionDeclarations _ _ = return ()++++prop_checkUnpassedInFunctions1 = verifyTree checkUnpassedInFunctions "foo() { echo $1; }; foo"+prop_checkUnpassedInFunctions2 = verifyNotTree checkUnpassedInFunctions "foo() { echo $1; };"+prop_checkUnpassedInFunctions3 = verifyNotTree checkUnpassedInFunctions "foo() { echo $lol; }; foo"+prop_checkUnpassedInFunctions4 = verifyNotTree checkUnpassedInFunctions "foo() { echo $0; }; foo"+prop_checkUnpassedInFunctions5 = verifyNotTree checkUnpassedInFunctions "foo() { echo $1; }; foo 'lol'; foo"+prop_checkUnpassedInFunctions6 = verifyNotTree checkUnpassedInFunctions "foo() { set -- *; echo $1; }; foo"+prop_checkUnpassedInFunctions7 = verifyTree checkUnpassedInFunctions "foo() { echo $1; }; foo; foo;"+prop_checkUnpassedInFunctions8 = verifyNotTree checkUnpassedInFunctions "foo() { echo $((1)); }; foo;"+prop_checkUnpassedInFunctions9 = verifyNotTree checkUnpassedInFunctions "foo() { echo $(($b)); }; foo;"+prop_checkUnpassedInFunctions10 = verifyNotTree checkUnpassedInFunctions "foo() { echo $!; }; foo;"+prop_checkUnpassedInFunctions11 = verifyNotTree checkUnpassedInFunctions "foo() { bar() { echo $1; }; bar baz; }; foo;"+prop_checkUnpassedInFunctions12 = verifyNotTree checkUnpassedInFunctions "foo() { echo ${!var*}; }; foo;"+prop_checkUnpassedInFunctions13 = verifyNotTree checkUnpassedInFunctions "# shellcheck disable=SC2120\nfoo() { echo $1; }\nfoo\n"+prop_checkUnpassedInFunctions14 = verifyTree checkUnpassedInFunctions "foo() { echo $#; }; foo"+prop_checkUnpassedInFunctions15 = verifyNotTree checkUnpassedInFunctions "foo() { echo ${1-x}; }; foo"+prop_checkUnpassedInFunctions16 = verifyNotTree checkUnpassedInFunctions "foo() { echo ${1:-x}; }; foo"+prop_checkUnpassedInFunctions17 = verifyNotTree checkUnpassedInFunctions "foo() { mycommand ${1+--verbose}; }; foo"+prop_checkUnpassedInFunctions18 = verifyNotTree checkUnpassedInFunctions "foo() { if mycheck; then foo ${1?Missing}; fi; }; foo"+checkUnpassedInFunctions params root =+ execWriter $ mapM_ warnForGroup referenceGroups+ where+ functionMap :: Map.Map String Token+ functionMap = Map.fromList $ execWriter $ doAnalysis (tell . maybeToList . findFunction) root++ findFunction t@(T_Function id _ _ name body)+ | any (isPositionalReference t) flow && not (any isPositionalAssignment flow)+ = return (name,t)+ where flow = getVariableFlow params body+ findFunction _ = Nothing++ isPositionalAssignment x =+ case x of+ Assignment (_, _, str, _) -> isPositional str+ _ -> False++ isPositionalReference function x =+ case x of+ Reference (_, t, str) -> isPositional str && t `isDirectChildOf` function && not (hasDefaultValue t)+ _ -> False++ isDirectChildOf child parent = fromMaybe False $ do+ function <- find (\x -> case x of+ T_Function {} -> True+ T_Script {} -> True -- for sourced files+ _ -> False) $+ getPath (parentMap params) child+ return $ getId parent == getId function++ referenceList :: [(String, Bool, Token)]+ referenceList = execWriter $+ doAnalysis (sequence_ . checkCommand) root++ checkCommand :: Token -> Maybe (Writer [(String, Bool, Token)] ())+ checkCommand t@(T_SimpleCommand _ _ (cmd:args)) = do+ str <- getLiteralString cmd+ guard $ Map.member str functionMap+ return $ tell [(str, null args, t)]+ checkCommand _ = Nothing++ isPositional str = str == "*" || str == "@" || str == "#"+ || (all isDigit str && str /= "0" && str /= "")++ -- True if t is a variable that specifies a default value,+ -- such as ${1-x} or ${1:-x}.+ hasDefaultValue t =+ case t of+ T_DollarBraced _ True l ->+ let str = concat $ oversimplify l+ in isDefaultValueModifier $ getBracedModifier str+ _ -> False++ isDefaultValueModifier str =+ case str of+ ':':c:_ -> c `elem` handlesDefault+ c:_ -> c `elem` handlesDefault+ _ -> False+ where handlesDefault = "-+?"++ isArgumentless (_, b, _) = b+ referenceGroups = Map.elems $ foldr updateWith Map.empty referenceList+ updateWith x@(name, _, _) = Map.insertWith (++) name [x]++ warnForGroup group =+ -- Allow ignoring SC2120 on the function to ignore all calls+ when (all isArgumentless group && not ignoring) $ do+ mapM_ suggestParams group+ warnForDeclaration func name+ where (name, func) = getFunction group+ ignoring = shouldIgnoreCode params 2120 func++ suggestParams (name, _, thing) =+ info (getId thing) 2119 $+ "Use " ++ (e4m name) ++ " \"$@\" if function's $1 should mean script's $1."+ warnForDeclaration func name =+ warn (getId func) 2120 $+ name ++ " references arguments, but none are ever passed."++ getFunction ((name, _, _):_) =+ (name, functionMap Map.! name)+++prop_checkOverridingPath1 = verify checkOverridingPath "PATH=\"$var/$foo\""+prop_checkOverridingPath2 = verify checkOverridingPath "PATH=\"mydir\""+prop_checkOverridingPath3 = verify checkOverridingPath "PATH=/cow/foo"+prop_checkOverridingPath4 = verifyNot checkOverridingPath "PATH=/cow/foo/bin"+prop_checkOverridingPath5 = verifyNot checkOverridingPath "PATH='/bin:/sbin'"+prop_checkOverridingPath6 = verifyNot checkOverridingPath "PATH=\"$var/$foo\" cmd"+prop_checkOverridingPath7 = verifyNot checkOverridingPath "PATH=$OLDPATH"+prop_checkOverridingPath8 = verifyNot checkOverridingPath "PATH=$PATH:/stuff"+checkOverridingPath _ (T_SimpleCommand _ vars []) =+ mapM_ checkVar vars+ where+ checkVar (T_Assignment id Assign "PATH" [] word)+ | not $ any (`isInfixOf` string) ["/bin", "/sbin" ] = do+ when ('/' `elem` string && ':' `notElem` string) $ notify id+ when (isLiteral word && ':' `notElem` string && '/' `notElem` string) $ notify id+ where string = concat $ oversimplify word+ checkVar _ = return ()+ notify id = warn id 2123 "PATH is the shell search path. Use another name."+checkOverridingPath _ _ = return ()++prop_checkTildeInPath1 = verify checkTildeInPath "PATH=\"$PATH:~/bin\""+prop_checkTildeInPath2 = verify checkTildeInPath "PATH='~foo/bin'"+prop_checkTildeInPath3 = verifyNot checkTildeInPath "PATH=~/bin"+prop_checkTildeInPath4 = verify checkTildeInPath "export PATH=\"$PATH:~/b\""+prop_checkTildeInPath5 = verify checkTildeInPath "export PATH=$PATH:\"~/c\""+prop_checkTildeInPath6 = verify checkTildeInPath "declare -x PATH=\"$PATH:~/d\""+prop_checkTildeInPath7 = verify checkTildeInPath "typeset -x PATH=\"$PATH:~/e\""+prop_checkTildeInPath8 = verify checkTildeInPath "f() { local PATH=\"$PATH:~/f\"; }"+-- Match T_Assignment directly so PATH=… args of export/declare/typeset/local+-- are covered, not only prefix assignments on a simple command.+checkTildeInPath _ (T_Assignment id Assign "PATH" [] (T_NormalWord _ parts))+ | any (\x -> isQuoted x && hasTilde x) parts =+ warn id 2147 "Literal tilde in PATH works poorly across programs."+ where+ hasTilde t = '~' `elem` onlyLiteralString t+ isQuoted T_DoubleQuoted {} = True+ isQuoted T_SingleQuoted {} = True+ isQuoted _ = False+checkTildeInPath _ _ = return ()++prop_checkUnsupported3 = verify checkUnsupported "#!/bin/sh\ncase foo in bar) baz ;& esac"+prop_checkUnsupported4 = verify checkUnsupported "#!/bin/ksh\ncase foo in bar) baz ;;& esac"+prop_checkUnsupported5 = verifyNot checkUnsupported "#!/bin/bash\necho \"${ ls; }\""+prop_checkUnsupported6 = verify checkUnsupported "#!/bin/ash\necho \"${ ls; }\""+checkUnsupported params t =+ unless (null support || (shellType params `elem` support)) $+ report name+ where+ (name, support) = shellSupport t+ report s = err (getId t) 2127 $+ "To use " ++ s ++ ", specify #!/usr/bin/env " +++ (intercalate " or " . map (map toLower . show) $ support)++-- TODO: Move more of these checks here+shellSupport t =+ case t of+ T_CaseExpression _ _ list -> forCase (map (\(a,_,_) -> a) list)+ T_DollarBraceCommandExpansion {} -> ("${ ..; } command expansion", [Bash, Ksh])+ _ -> ("", [])+ where+ forCase seps | CaseContinue `elem` seps = ("cases with ;;&", [Bash])+ forCase seps | CaseFallThrough `elem` seps = ("cases with ;&", [Bash, Ksh])+ forCase _ = ("", [])+++groupWith f = groupBy ((==) `on` f)++prop_checkMultipleAppends1 = verify checkMultipleAppends "foo >> file; bar >> file; baz >> file;"+prop_checkMultipleAppends2 = verify checkMultipleAppends "foo >> file; bar | grep f >> file; baz >> file;"+prop_checkMultipleAppends3 = verifyNot checkMultipleAppends "foo < file; bar < file; baz < file;"+checkMultipleAppends params t =+ mapM_ checkList $ getCommandSequences t+ where+ checkList list =+ mapM_ checkGroup (groupWith (fmap fst) $ map getTarget list)+ checkGroup (Just (_,id):_:_:_) =+ style id 2129+ "Consider using { cmd1; cmd2; } >> file instead of individual redirects."+ checkGroup _ = return ()+ getTarget (T_Annotation _ _ t) = getTarget t+ getTarget (T_Pipeline _ _ args@(_:_)) = getTarget (last args)+ getTarget (T_Redirecting id list _) = do+ file <- mapMaybe getAppend list !!! 0+ return (file, id)+ getTarget _ = Nothing+ getAppend (T_FdRedirect _ _ (T_IoFile _ T_DGREAT {} f)) = return f+ getAppend _ = Nothing+++prop_checkSuspiciousIFS1 = verify checkSuspiciousIFS "IFS=\"\\n\""+prop_checkSuspiciousIFS2 = verifyNot checkSuspiciousIFS "IFS=$'\\t'"+prop_checkSuspiciousIFS3 = verify checkSuspiciousIFS "IFS=' \\t\\n'"+checkSuspiciousIFS params (T_Assignment _ _ "IFS" [] value) =+ mapM_ check $ getLiteralString value+ where+ hasDollarSingle = shellType params == Bash || shellType params == Ksh+ n = if hasDollarSingle then "$'\\n'" else "'<literal linefeed here>'"+ t = if hasDollarSingle then "$'\\t'" else "\"$(printf '\\t')\""+ check value =+ case value of+ "\\n" -> suggest n+ "\\t" -> suggest t+ x | '\\' `elem` x -> suggest2 "a literal backslash"+ x | 'n' `elem` x -> suggest2 "the literal letter 'n'"+ x | 't' `elem` x -> suggest2 "the literal letter 't'"+ _ -> return ()+ suggest r = warn (getId value) 2141 $ "This backslash is literal. Did you mean IFS=" ++ r ++ " ?"+ suggest2 desc = warn (getId value) 2141 $ "This IFS value contains " ++ desc ++ ". For tabs/linefeeds/escapes, use $'..', literal, or printf."+checkSuspiciousIFS _ _ = return ()+++prop_checkGrepQ1 = verify checkShouldUseGrepQ "[[ $(foo | grep bar) ]]"+prop_checkGrepQ2 = verify checkShouldUseGrepQ "[ -z $(fgrep lol) ]"+prop_checkGrepQ3 = verify checkShouldUseGrepQ "[ -n \"$(foo | zgrep lol)\" ]"+prop_checkGrepQ4 = verifyNot checkShouldUseGrepQ "[ -z $(grep bar | cmd) ]"+prop_checkGrepQ5 = verifyNot checkShouldUseGrepQ "rm $(ls | grep file)"+prop_checkGrepQ6 = verifyNot checkShouldUseGrepQ "[[ -n $(pgrep foo) ]]"+checkShouldUseGrepQ params t =+ sequence_ $ case t of+ TC_Nullary id _ token -> check id True token+ TC_Unary id _ "-n" token -> check id True token+ TC_Unary id _ "-z" token -> check id False token+ _ -> fail "not check"+ where+ check id bool token = do+ name <- getFinalGrep token+ let op = if bool then "-n" else "-z"+ let flip = if bool then "" else "! "+ return . style id 2143 $+ "Use " ++ flip ++ name ++ " -q instead of " +++ "comparing output with [ " ++ op ++ " .. ]."++ getFinalGrep t = do+ cmds <- getPipeline t+ guard . not . null $ cmds+ name <- getCommandBasename $ last cmds+ guard . isGrep $ name+ return name+ getPipeline t =+ case t of+ T_NormalWord _ [x] -> getPipeline x+ T_DoubleQuoted _ [x] -> getPipeline x+ T_DollarExpansion _ [x] -> getPipeline x+ T_Pipeline _ _ cmds -> return cmds+ _ -> fail "unknown"+ isGrep = (`elem` ["grep", "egrep", "fgrep", "bz3grep", "bzgrep", "xzgrep", "zgrep", "zipgrep", "zstdgrep"])++prop_checkTestArgumentSplitting1 = verify checkTestArgumentSplitting "[ -e *.mp3 ]"+prop_checkTestArgumentSplitting2 = verifyNot checkTestArgumentSplitting "[[ $a == *b* ]]"+prop_checkTestArgumentSplitting3 = verify checkTestArgumentSplitting "[[ *.png == '' ]]"+prop_checkTestArgumentSplitting4 = verify checkTestArgumentSplitting "[[ foo == f{o,oo,ooo} ]]"+prop_checkTestArgumentSplitting5 = verify checkTestArgumentSplitting "[[ $@ ]]"+prop_checkTestArgumentSplitting6 = verify checkTestArgumentSplitting "[ -e $@ ]"+prop_checkTestArgumentSplitting7 = verify checkTestArgumentSplitting "[ $@ == $@ ]"+prop_checkTestArgumentSplitting8 = verify checkTestArgumentSplitting "[[ $@ = $@ ]]"+prop_checkTestArgumentSplitting9 = verifyNot checkTestArgumentSplitting "[[ foo =~ bar{1,2} ]]"+prop_checkTestArgumentSplitting10 = verifyNot checkTestArgumentSplitting "[ \"$@\" ]"+prop_checkTestArgumentSplitting11 = verify checkTestArgumentSplitting "[[ \"$@\" ]]"+prop_checkTestArgumentSplitting12 = verify checkTestArgumentSplitting "[ *.png ]"+prop_checkTestArgumentSplitting13 = verify checkTestArgumentSplitting "[ \"$@\" == \"\" ]"+prop_checkTestArgumentSplitting14 = verify checkTestArgumentSplitting "[[ \"$@\" == \"\" ]]"+prop_checkTestArgumentSplitting15 = verifyNot checkTestArgumentSplitting "[[ \"$*\" == \"\" ]]"+prop_checkTestArgumentSplitting16 = verifyNot checkTestArgumentSplitting "[[ -v foo[123] ]]"+prop_checkTestArgumentSplitting17 = verifyNot checkTestArgumentSplitting "#!/bin/ksh\n[ -e foo* ]"+prop_checkTestArgumentSplitting18 = verify checkTestArgumentSplitting "#!/bin/ksh\n[ -d foo* ]"+prop_checkTestArgumentSplitting19 = verifyNot checkTestArgumentSplitting "[[ var[x] -eq 2*3 ]]"+prop_checkTestArgumentSplitting20 = verify checkTestArgumentSplitting "[ var[x] -eq 2 ]"+prop_checkTestArgumentSplitting21 = verify checkTestArgumentSplitting "[ 6 -eq 2*3 ]"+checkTestArgumentSplitting :: Parameters -> Token -> Writer [TokenComment] ()+checkTestArgumentSplitting params t =+ case t of+ (TC_Unary _ typ op token) | isGlob token ->+ if op == "-v"+ then+ when (typ == SingleBracket) $+ err (getId token) 2208 $+ "Use [[ ]] or quote arguments to -v to avoid glob expansion."+ else+ if (typ == SingleBracket && shellType params == Ksh)+ then+ -- Ksh appears to stop processing after unrecognized tokens, so operators+ -- will effectively work with globs, but only the first match.+ when (op `elem` [['-', c] | c <- "bcdfgkprsuwxLhNOGRS" ]) $+ warn (getId token) 2245 $+ op ++ " only applies to the first expansion of this glob. Use a loop to check any/all."+ else+ err (getId token) 2144 $+ op ++ " doesn't work with globs. Use a for loop."++ (TC_Nullary _ typ token) -> do+ checkBraces typ token+ checkGlobs typ token+ when (typ == DoubleBracket) $+ checkArrays typ token++ (TC_Unary _ typ op token) -> checkAll typ token++ (TC_Binary _ typ op lhs rhs) | op `elem` arithmeticBinaryTestOps ->+ if typ == DoubleBracket+ then+ mapM_ (\c -> do+ checkArrays typ c+ checkBraces typ c) [lhs, rhs]+ else+ mapM_ (\c -> do+ checkNumericalGlob typ c+ checkArrays typ c+ checkBraces typ c) [lhs, rhs]++ (TC_Binary _ typ op lhs rhs) ->+ if op `elem` ["=", "==", "!=", "=~"]+ then do+ checkAll typ lhs+ checkArrays typ rhs+ checkBraces typ rhs+ else mapM_ (checkAll typ) [lhs, rhs]+ _ -> return ()+ where+ checkAll typ token = do+ checkArrays typ token+ checkBraces typ token+ checkGlobs typ token++ checkArrays typ token =+ when (any isArrayExpansion $ getWordParts token) $+ if typ == SingleBracket+ then warn (getId token) 2198 "Arrays don't work as operands in [ ]. Use a loop (or concatenate with * instead of @)."+ else err (getId token) 2199 "Arrays implicitly concatenate in [[ ]]. Use a loop (or explicit * instead of @)."++ checkBraces typ token =+ when (any isBraceExpansion $ getWordParts token) $+ if typ == SingleBracket+ then warn (getId token) 2200 "Brace expansions don't work as operands in [ ]. Use a loop."+ else err (getId token) 2201 "Brace expansion doesn't happen in [[ ]]. Use a loop."++ checkGlobs typ token =+ when (isGlob token) $+ if typ == SingleBracket+ then warn (getId token) 2202 "Globs don't work as operands in [ ]. Use a loop."+ else err (getId token) 2203 "Globs are ignored in [[ ]] except right of =/!=. Use a loop."++ checkNumericalGlob SingleBracket token =+ -- var[x] and x*2 look like globs+ when (shellType params /= Ksh && isGlob token) $+ err (getId token) 2255 "[ ] does not apply arithmetic evaluation. Evaluate with $((..)) for numbers, or use string comparator for strings."+++prop_checkReadWithoutR1 = verify checkReadWithoutR "read -a foo"+prop_checkReadWithoutR2 = verifyNot checkReadWithoutR "read -ar foo"+prop_checkReadWithoutR3 = verifyNot checkReadWithoutR "read -t 0"+prop_checkReadWithoutR4 = verifyNot checkReadWithoutR "read -t 0 && read --d '' -r bar"+prop_checkReadWithoutR5 = verifyNot checkReadWithoutR "read -t 0 foo < file.txt"+prop_checkReadWithoutR6 = verifyNot checkReadWithoutR "read -u 3 -t 0"+checkReadWithoutR _ t@T_SimpleCommand {} | t `isUnqualifiedCommand` "read"+ && "r" `notElem` map snd flags && not has_t0 =+ info (getId $ getCommandTokenOrThis t) 2162 "read without -r will mangle backslashes."+ where+ flags = getAllFlags t+ has_t0 = Just "0" == do+ parsed <- getGnuOpts flagsForRead $ arguments t+ (_, t) <- lookup "t" parsed+ getLiteralString t++checkReadWithoutR _ _ = return ()++prop_checkCpLegacyR1 = verify checkCpLegacyR "cp -r foo bar"+prop_checkCpLegacyR2 = verifyNot checkCpLegacyR "cp -R foo bar"+checkCpLegacyR params t@T_SimpleCommand {} | t `isUnqualifiedCommand` "cp" = case legacyFlag of+ Just (t, _) -> warnWithFix (getId t) 2336 "cp -r behavior is implementation-defined"+ (fixWith [replaceToken (getId t) params "-R"])+ Nothing -> return ()+ where+ flags = getAllFlags t+ legacyFlag = find ((=="r") . snd) flags+checkCpLegacyR _ _ = return ()++prop_checkUncheckedCd1 = verifyTree checkUncheckedCdPushdPopd "cd ~/src; rm -r foo"+prop_checkUncheckedCd2 = verifyNotTree checkUncheckedCdPushdPopd "cd ~/src || exit; rm -r foo"+prop_checkUncheckedCd3 = verifyNotTree checkUncheckedCdPushdPopd "set -e; cd ~/src; rm -r foo"+prop_checkUncheckedCd4 = verifyNotTree checkUncheckedCdPushdPopd "if cd foo; then rm foo; fi"+prop_checkUncheckedCd5 = verifyTree checkUncheckedCdPushdPopd "if true; then cd foo; fi"+prop_checkUncheckedCd6 = verifyNotTree checkUncheckedCdPushdPopd "cd .."+prop_checkUncheckedCd7 = verifyNotTree checkUncheckedCdPushdPopd "#!/bin/bash -e\ncd foo\nrm bar"+prop_checkUncheckedCd8 = verifyNotTree checkUncheckedCdPushdPopd "set -o errexit; cd foo; rm bar"+prop_checkUncheckedCd9 = verifyTree checkUncheckedCdPushdPopd "builtin cd ~/src; rm -r foo"+prop_checkUncheckedPushd1 = verifyTree checkUncheckedCdPushdPopd "pushd ~/src; rm -r foo"+prop_checkUncheckedPushd2 = verifyNotTree checkUncheckedCdPushdPopd "pushd ~/src || exit; rm -r foo"+prop_checkUncheckedPushd3 = verifyNotTree checkUncheckedCdPushdPopd "set -e; pushd ~/src; rm -r foo"+prop_checkUncheckedPushd4 = verifyNotTree checkUncheckedCdPushdPopd "if pushd foo; then rm foo; fi"+prop_checkUncheckedPushd5 = verifyTree checkUncheckedCdPushdPopd "if true; then pushd foo; fi"+prop_checkUncheckedPushd6 = verifyNotTree checkUncheckedCdPushdPopd "pushd .."+prop_checkUncheckedPushd7 = verifyNotTree checkUncheckedCdPushdPopd "#!/bin/bash -e\npushd foo\nrm bar"+prop_checkUncheckedPushd8 = verifyNotTree checkUncheckedCdPushdPopd "set -o errexit; pushd foo; rm bar"+prop_checkUncheckedPushd9 = verifyNotTree checkUncheckedCdPushdPopd "pushd -n foo"+prop_checkUncheckedPopd1 = verifyTree checkUncheckedCdPushdPopd "popd; rm -r foo"+prop_checkUncheckedPopd2 = verifyNotTree checkUncheckedCdPushdPopd "popd || exit; rm -r foo"+prop_checkUncheckedPopd3 = verifyNotTree checkUncheckedCdPushdPopd "set -e; popd; rm -r foo"+prop_checkUncheckedPopd4 = verifyNotTree checkUncheckedCdPushdPopd "if popd; then rm foo; fi"+prop_checkUncheckedPopd5 = verifyTree checkUncheckedCdPushdPopd "if true; then popd; fi"+prop_checkUncheckedPopd6 = verifyTree checkUncheckedCdPushdPopd "popd"+prop_checkUncheckedPopd7 = verifyNotTree checkUncheckedCdPushdPopd "#!/bin/bash -e\npopd\nrm bar"+prop_checkUncheckedPopd8 = verifyNotTree checkUncheckedCdPushdPopd "set -o errexit; popd; rm bar"+prop_checkUncheckedPopd9 = verifyNotTree checkUncheckedCdPushdPopd "popd -n foo"+prop_checkUncheckedPopd10 = verifyNotTree checkUncheckedCdPushdPopd "cd ../.."+prop_checkUncheckedPopd11 = verifyNotTree checkUncheckedCdPushdPopd "cd ../.././.."+prop_checkUncheckedPopd12 = verifyNotTree checkUncheckedCdPushdPopd "cd /"+prop_checkUncheckedPopd13 = verifyTree checkUncheckedCdPushdPopd "cd ../../.../.."+prop_checkUncheckedCdInFunction1 = verifyNotTree checkUncheckedCdPushdPopd "#!/bin/bash\nfoo() {\n cd /abc\n}"+prop_checkUncheckedCdInFunction2 = verifyNotTree checkUncheckedCdPushdPopd "foo() { cd /abc; return; }"+prop_checkUncheckedCdInFunction3 = verifyNotTree checkUncheckedCdPushdPopd "foo() { cd /abc; exit; }"+prop_checkUncheckedCdInFunction4 = verifyTree checkUncheckedCdPushdPopd "foo() { cd /abc; return 0; }"+prop_checkUncheckedCdInFunction5 = verifyTree checkUncheckedCdPushdPopd "foo() { cd /abc; return > output; }"+prop_checkUncheckedCdInFunction6 = verifyTree checkUncheckedCdPushdPopd "foo() { cd /abc; return | cat; }"+prop_checkUncheckedCdInFunction7 = verifyNotTree checkUncheckedCdPushdPopd "foo() { cd /abc; return $?; }"+prop_checkUncheckedCdInFunction8 = verifyNotTree checkUncheckedCdPushdPopd "foo() { cd /abc; exit $?; }"++checkUncheckedCdPushdPopd params root =+ if hasErrexit params then+ []+ else execWriter $ doAnalysis checkElement root+ where+ checkElement t@T_SimpleCommand {}+ | name `elem` ["cd", "pushd", "popd"]+ && not (isSafeDir t)+ && not (name `elem` ["pushd", "popd"] && ("n" `elem` map snd (getAllFlags t)))+ && not (isLastCommandInFunction t)+ && not (isCondition $ getPath (parentMap params) t) =+ warnWithFix (getId t) 2164+ ("Use '" ++ name ++ " ... || exit' or '" ++ name ++ " ... || return' in case " ++ name ++ " fails.")+ (fixWith [replaceEnd (getId t) params 0 " || exit"])+ where name = getName t+ checkElement _ = return ()+ getName t = fromMaybe "" $ getCommandName t+ isLastCommandInFunction t =+ go $ NE.tail $ getPath (parentMap params) t+ where+ go (child:T_BraceGroup _ commands:T_Function {}:_) =+ case dropWhile ((/= getId child) . getId) commands of+ [_] -> True+ [_, T_Pipeline _ [] [T_Redirecting _ [] (T_SimpleCommand _ [] (cmd:args))]] ->+ getLiteralString cmd `elem` [Just "return", Just "exit"] && case args of+ [] -> True+ [T_NormalWord _ [T_DollarBraced _ False status]] -> getLiteralString status == Just "?"+ _ -> False+ _ -> False+ go (_:rest) = go rest+ go [] = False+ isSafeDir t = case oversimplify t of+ [_, str] -> str `matches` regex+ _ -> False+ regex = mkRegex "^/*((\\.|\\.\\.)/+)*(\\.|\\.\\.)?$"++prop_checkLoopVariableReassignment1 = verify checkLoopVariableReassignment "for i in *; do for i in *.bar; do true; done; done"+prop_checkLoopVariableReassignment2 = verify checkLoopVariableReassignment "for i in *; do for((i=0; i<3; i++)); do true; done; done"+prop_checkLoopVariableReassignment3 = verifyNot checkLoopVariableReassignment "for i in *; do for j in *.bar; do true; done; done"+prop_checkLoopVariableReassignment4 = verifyNot checkLoopVariableReassignment "for _ in *; do for _ in *.bar; do true; done; done"+checkLoopVariableReassignment params token =+ sequence_ $ case token of+ T_ForIn {} -> check+ T_ForArithmetic {} -> check+ _ -> Nothing+ where+ check = do+ str <- loopVariable token+ guard $ str /= "_"+ next <- find (\x -> loopVariable x == Just str) path+ return $ do+ warn (getId token) 2165 "This nested loop overrides the index variable of its parent."+ warn (getId next) 2167 "This parent loop has its index variable overridden."+ path = NE.tail $ getPath (parentMap params) token+ loopVariable :: Token -> Maybe String+ loopVariable t =+ case t of+ T_ForIn _ s _ _ -> return s+ T_ForArithmetic _+ (TA_Sequence _+ [TA_Assignment _ "="+ (TA_Variable _ var _ ) _])+ _ _ _ -> return var+ _ -> fail "not loop"++prop_checkTrailingBracket1 = verify checkTrailingBracket "if -z n ]]; then true; fi "+prop_checkTrailingBracket2 = verifyNot checkTrailingBracket "if [[ -z n ]]; then true; fi "+prop_checkTrailingBracket3 = verify checkTrailingBracket "a || b ] && thing"+prop_checkTrailingBracket4 = verifyNot checkTrailingBracket "run [ foo ]"+prop_checkTrailingBracket5 = verifyNot checkTrailingBracket "run bar ']'"+checkTrailingBracket _ token =+ case token of+ T_SimpleCommand _ _ tokens@(_:_) -> check (last tokens) token+ _ -> return ()+ where+ check (T_NormalWord id [T_Literal _ str]) command+ | str `elem` [ "]]", "]" ]+ && opposite `notElem` parameters+ = warn id 2171 $+ "Found trailing " ++ str ++ " outside test. Add missing " ++ opposite ++ " or quote if intentional."+ where+ opposite = invert str+ parameters = oversimplify command+ check _ _ = return ()+ invert s =+ case s of+ "]]" -> "[["+ "]" -> "["+ x -> x++prop_checkReturnAgainstZero1 = verify checkReturnAgainstZero "[ $? -eq 0 ]"+prop_checkReturnAgainstZero2 = verify checkReturnAgainstZero "[[ \"$?\" -gt 0 ]]"+prop_checkReturnAgainstZero3 = verify checkReturnAgainstZero "[[ 0 -ne $? ]]"+prop_checkReturnAgainstZero4 = verifyNot checkReturnAgainstZero "[[ $? -eq 4 ]]"+prop_checkReturnAgainstZero5 = verify checkReturnAgainstZero "[[ 0 -eq $? ]]"+prop_checkReturnAgainstZero6 = verifyNot checkReturnAgainstZero "[[ $R -eq 0 ]]"+prop_checkReturnAgainstZero7 = verify checkReturnAgainstZero "(( $? == 0 ))"+prop_checkReturnAgainstZero8 = verify checkReturnAgainstZero "(( $? ))"+prop_checkReturnAgainstZero9 = verify checkReturnAgainstZero "(( ! $? ))"+prop_checkReturnAgainstZero10 = verifyNot checkReturnAgainstZero "x=$(( $? > 0 ))"+prop_checkReturnAgainstZero11 = verify checkReturnAgainstZero "(( ! ! ! $? ))"+prop_checkReturnAgainstZero12 = verify checkReturnAgainstZero "[ ! $? -eq 0 ]"+prop_checkReturnAgainstZero13 = verifyNot checkReturnAgainstZero "(( ! $? && $? > 42))"+prop_checkReturnAgainstZero14 = verifyNot checkReturnAgainstZero "[[ -e foo || $? -eq 0 ]]"+prop_checkReturnAgainstZero15 = verifyNot checkReturnAgainstZero "(( $?, n=1 ))"+prop_checkReturnAgainstZero16 = verifyNot checkReturnAgainstZero "(( $? || $? == 4 ))"+prop_checkReturnAgainstZero17 = verifyNot checkReturnAgainstZero "(( $? + 0 ))"+prop_checkReturnAgainstZero18 = verifyNot checkReturnAgainstZero "f() { if [ $? -eq 0 ]; then :; fi; }"+prop_checkReturnAgainstZero19 = verifyNot checkReturnAgainstZero "f() ( [ $? -eq 0 ] || exit 42; )"+prop_checkReturnAgainstZero20 = verify checkReturnAgainstZero "f() { if :; then x; [ $? -eq 0 ] && exit; fi; }"+prop_checkReturnAgainstZero21 = verify checkReturnAgainstZero "(( ( $? ) ))"+prop_checkReturnAgainstZero22 = verify checkReturnAgainstZero "[[ ( $? -eq 0 ) ]]"+checkReturnAgainstZero params token =+ case token of+ TC_Binary id _ op lhs rhs -> check op lhs rhs+ TA_Binary id op lhs rhs+ | op `elem` [">", "<", ">=", "<=", "==", "!="] -> check op lhs rhs+ TA_Unary id op@"!" exp+ | isExitCode exp -> message (checksSuccessLhs op) (getId exp)+ TA_Sequence _ [exp]+ | isExitCode exp -> message False (getId exp)+ _ -> return ()+ where+ -- We don't want to warn about composite expressions like+ -- [[ $? -eq 0 || $? -eq 4 ]] since these can be annoying to rewrite.+ isOnlyTestInCommand t =+ case NE.tail $ getPath (parentMap params) t of+ (T_Condition {}):_ -> True+ (T_Arithmetic {}):_ -> True+ (TA_Sequence _ [_]):(T_Arithmetic {}):_ -> True++ -- Some negations and groupings are also fine+ next@(TC_Unary _ _ "!" _):_ -> isOnlyTestInCommand next+ next@(TA_Unary _ "!" _):_ -> isOnlyTestInCommand next+ next@(TC_Group {}):_ -> isOnlyTestInCommand next+ next@(TA_Sequence _ [_]):_ -> isOnlyTestInCommand next+ next@(TA_Parenthesis _ _):_ -> isOnlyTestInCommand next+ _ -> False++ -- TODO: Do better $? tracking and filter on whether+ -- the target command is in the same function+ getFirstCommandInFunction = f+ where+ f t = case t of+ T_Function _ _ _ _ x -> f x+ T_BraceGroup _ (x:_) -> f x+ T_Subshell _ (x:_) -> f x+ T_Annotation _ _ x -> f x+ T_AndIf _ x _ -> f x+ T_OrIf _ x _ -> f x+ T_Pipeline _ _ (x:_) -> f x+ T_Redirecting _ _ (T_IfExpression _ (((x:_),_):_) _) -> f x+ x -> x++ isFirstCommandInFunction = fromMaybe False $ do+ let path = getPath (parentMap params) token+ func <- find isFunction path+ cmd <- getClosestCommand (parentMap params) token+ return $ getId cmd == getId (getFirstCommandInFunction func)++ -- Is "$? op 0" trying to check if the command succeeded?+ checksSuccessLhs op = not $ op `elem` ["-gt", "-ne", "!=", "!"]+ -- Is "0 op $?" trying to check if the command succeeded?+ checksSuccessRhs op = op `notElem` ["-ne", "!="]++ check op lhs rhs =+ if isZero rhs && isExitCode lhs+ then message (checksSuccessLhs op) (getId lhs)+ else when (isZero lhs && isExitCode rhs) $ message (checksSuccessRhs op) (getId rhs)+ isZero t = getLiteralString t == Just "0"+ isExitCode t =+ case getWordParts t of+ [T_DollarBraced _ _ l] -> concat (oversimplify l) == "?"+ _ -> False++ message forSuccess id = when (isOnlyTestInCommand token && not isFirstCommandInFunction) $ style id 2181 $+ "Check exit code directly with e.g. 'if " ++ (if forSuccess then "" else "! ") ++ "mycmd;', not indirectly with $?."+++prop_checkRedirectedNowhere1 = verify checkRedirectedNowhere "> file"+prop_checkRedirectedNowhere2 = verify checkRedirectedNowhere "> file | grep foo"+prop_checkRedirectedNowhere3 = verify checkRedirectedNowhere "grep foo | > bar"+prop_checkRedirectedNowhere4 = verifyNot checkRedirectedNowhere "grep foo > bar"+prop_checkRedirectedNowhere5 = verifyNot checkRedirectedNowhere "foo | grep bar > baz"+prop_checkRedirectedNowhere6 = verifyNot checkRedirectedNowhere "var=$(value) 2> /dev/null"+prop_checkRedirectedNowhere7 = verifyNot checkRedirectedNowhere "var=$(< file)"+prop_checkRedirectedNowhere8 = verifyNot checkRedirectedNowhere "var=`< file`"+checkRedirectedNowhere params token =+ case token of+ T_Pipeline _ _ [single] -> sequence_ $ do+ redir <- getDanglingRedirect single+ guard . not $ isInExpansion token+ return $ warn (getId redir) 2188 "This redirection doesn't have a command. Move to its command (or use 'true' as no-op)."++ T_Pipeline _ _ list -> forM_ list $ \x -> sequence_ $ do+ redir <- getDanglingRedirect x+ return $ err (getId redir) 2189 "You can't have | between this redirection and the command it should apply to."++ _ -> return ()+ where+ isInExpansion t =+ case NE.tail $ getPath (parentMap params) t of+ T_DollarExpansion _ [_] : _ -> True+ T_Backticked _ [_] : _ -> True+ t@T_Annotation {} : _ -> isInExpansion t+ _ -> False+ getDanglingRedirect token =+ case token of+ T_Redirecting _ (first:_) (T_SimpleCommand _ [] []) -> return first+ _ -> Nothing+++prop_checkArrayAssignmentIndices1 = verifyTree checkArrayAssignmentIndices "declare -A foo; foo=(bar)"+prop_checkArrayAssignmentIndices2 = verifyNotTree checkArrayAssignmentIndices "declare -a foo; foo=(bar)"+prop_checkArrayAssignmentIndices3 = verifyNotTree checkArrayAssignmentIndices "declare -A foo; foo=([i]=bar)"+prop_checkArrayAssignmentIndices4 = verifyTree checkArrayAssignmentIndices "typeset -A foo; foo+=(bar)"+prop_checkArrayAssignmentIndices5 = verifyTree checkArrayAssignmentIndices "arr=( [foo]= bar )"+prop_checkArrayAssignmentIndices6 = verifyTree checkArrayAssignmentIndices "arr=( [foo] = bar )"+prop_checkArrayAssignmentIndices7 = verifyNotTree checkArrayAssignmentIndices "arr=( var=value )"+prop_checkArrayAssignmentIndices8 = verifyNotTree checkArrayAssignmentIndices "arr=( [foo]=bar )"+prop_checkArrayAssignmentIndices9 = verifyNotTree checkArrayAssignmentIndices "arr=( [foo]=\"\" )"+prop_checkArrayAssignmentIndices10 = verifyTree checkArrayAssignmentIndices "declare -A arr; arr=( var=value )"+prop_checkArrayAssignmentIndices11 = verifyTree checkArrayAssignmentIndices "arr=( 1=value )"+prop_checkArrayAssignmentIndices12 = verifyTree checkArrayAssignmentIndices "arr=( $a=value )"+prop_checkArrayAssignmentIndices13 = verifyTree checkArrayAssignmentIndices "arr=( $((1+1))=value )"+checkArrayAssignmentIndices params root =+ runNodeAnalysis check params root+ where+ assocs = getAssociativeArrays root+ check _ t =+ case t of+ T_Assignment _ _ name [] (T_Array _ list) ->+ let isAssoc = name `elem` assocs in+ mapM_ (checkElement isAssoc) list+ _ -> return ()++ checkElement isAssociative t =+ case t of+ T_IndexedElement _ _ (T_Literal id "") ->+ warn id 2192 "This array element has no value. Remove spaces after = or use \"\" for empty string."+ T_IndexedElement {} ->+ return ()++ T_NormalWord _ parts ->+ let literalEquals = do+ T_Literal id str <- parts+ let (before, after) = break ('=' ==) str+ guard $ all isDigit before && not (null after)+ return $ warnWithFix id 2191 "The = here is literal. To assign by index, use ( [index]=value ) with no spaces. To keep as literal, quote it." (surroundWith id params "\"")+ in+ if null literalEquals && isAssociative+ then warn (getId t) 2190 "Elements in associative arrays need index, e.g. array=( [index]=value ) ."+ else sequence_ literalEquals++ _ -> return ()+++prop_checkUnmatchableCases1 = verify checkUnmatchableCases "case foo in bar) true; esac"+prop_checkUnmatchableCases2 = verify checkUnmatchableCases "case foo-$bar in ??|*) true; esac"+prop_checkUnmatchableCases3 = verify checkUnmatchableCases "case foo in foo) true; esac"+prop_checkUnmatchableCases4 = verifyNot checkUnmatchableCases "case foo-$bar in foo*|*bar|*baz*) true; esac"+prop_checkUnmatchableCases5 = verify checkUnmatchableCases "case $f in *.txt) true;; f??.txt) false;; esac"+prop_checkUnmatchableCases6 = verifyNot checkUnmatchableCases "case $f in ?*) true;; *) false;; esac"+prop_checkUnmatchableCases7 = verifyNot checkUnmatchableCases "case $f in $(x)) true;; asdf) false;; esac"+prop_checkUnmatchableCases8 = verify checkUnmatchableCases "case $f in cow) true;; bar|cow) false;; esac"+prop_checkUnmatchableCases9 = verifyNot checkUnmatchableCases "case $f in x) true;;& x) false;; esac"+checkUnmatchableCases params t =+ case t of+ T_CaseExpression _ word list -> do+ -- Check all patterns for whether they can ever match+ let allpatterns = concatMap snd3 list+ -- Check only the non-fallthrough branches for shadowing+ let breakpatterns = concatMap snd3 $ filter (\x -> fst3 x == CaseBreak) list++ if isConstant word+ then warn (getId word) 2194+ "This word is constant. Did you forget the $ on a variable?"+ else mapM_ (check $ wordToPseudoGlob word) allpatterns++ let exactGlobs = tupMap wordToExactPseudoGlob breakpatterns+ let fuzzyGlobs = tupMap wordToPseudoGlob breakpatterns+ let dominators = zip exactGlobs (tails $ drop 1 fuzzyGlobs)++ mapM_ checkDoms dominators++ _ -> return ()+ where+ fst3 (x,_,_) = x+ snd3 (_,x,_) = x+ tp = tokenPositions params+ check target candidate = unless (pseudoGlobsCanOverlap target $ wordToPseudoGlob candidate) $+ warn (getId candidate) 2195+ "This pattern will never match the case statement's word. Double check them."++ tupMap f l = map (\x -> (x, f x)) l+ checkDoms ((glob, Just x), rest) =+ forM_ (find (\(_, p) -> x `pseudoGlobIsSuperSetof` p) rest) $+ \(first,_) -> do+ warn (getId glob) 2221 $ "This pattern always overrides a later one" <> patternContext (getId first)+ warn (getId first) 2222 $ "This pattern never matches because of a previous pattern" <> patternContext (getId glob)+ where+ patternContext :: Id -> String+ patternContext id =+ case posLine . fst <$> Map.lookup id tp of+ Just l -> " on line " <> show l <> "."+ _ -> "."+ checkDoms _ = return ()+++prop_checkSubshellAsTest1 = verify checkSubshellAsTest "( -e file )"+prop_checkSubshellAsTest2 = verify checkSubshellAsTest "( 1 -gt 2 )"+prop_checkSubshellAsTest3 = verifyNot checkSubshellAsTest "( grep -c foo bar )"+prop_checkSubshellAsTest4 = verifyNot checkSubshellAsTest "[ 1 -gt 2 ]"+prop_checkSubshellAsTest5 = verify checkSubshellAsTest "( -e file && -x file )"+prop_checkSubshellAsTest6 = verify checkSubshellAsTest "( -e file || -x file && -t 1 )"+prop_checkSubshellAsTest7 = verify checkSubshellAsTest "( ! -d file )"+checkSubshellAsTest _ t =+ case t of+ T_Subshell id [w] -> check id w+ _ -> return ()+ where+ check id t = case t of+ (T_Banged _ w) -> check id w+ (T_AndIf _ w _) -> check id w+ (T_OrIf _ w _) -> check id w+ (T_Pipeline _ _ [T_Redirecting _ _ (T_SimpleCommand _ [] (first:second:_))]) ->+ checkParams id first second+ _ -> return ()+++ checkParams id first second = do+ when (maybe False (`elem` unaryTestOps) $ getLiteralString first) $+ err id 2204 "(..) is a subshell. Did you mean [ .. ], a test expression?"+ when (maybe False (`elem` binaryTestOps) $ getLiteralString second) $+ warn id 2205 "(..) is a subshell. Did you mean [ .. ], a test expression?"+++prop_checkSplittingInArrays1 = verify checkSplittingInArrays "a=( $var )"+prop_checkSplittingInArrays2 = verify checkSplittingInArrays "a=( $(cmd) )"+prop_checkSplittingInArrays3 = verifyNot checkSplittingInArrays "a=( \"$var\" )"+prop_checkSplittingInArrays4 = verifyNot checkSplittingInArrays "a=( \"$(cmd)\" )"+prop_checkSplittingInArrays5 = verifyNot checkSplittingInArrays "a=( $! $$ $# )"+prop_checkSplittingInArrays6 = verifyNot checkSplittingInArrays "a=( ${#arr[@]} )"+prop_checkSplittingInArrays7 = verifyNot checkSplittingInArrays "a=( foo{1,2} )"+prop_checkSplittingInArrays8 = verifyNot checkSplittingInArrays "a=( * )"+checkSplittingInArrays params t =+ case t of+ T_Array _ elements -> mapM_ check elements+ _ -> return ()+ where+ check word = case word of+ T_NormalWord _ parts -> mapM_ checkPart parts+ _ -> return ()+ checkPart part = case part of+ T_DollarExpansion id _ -> forCommand id+ T_DollarBraceCommandExpansion id _ _ -> forCommand id+ T_Backticked id _ -> forCommand id+ T_DollarBraced id _ str |+ not (isCountingReference part)+ && not (isQuotedAlternativeReference part)+ && getBracedReference (concat $ oversimplify str) `notElem` variablesWithoutSpaces+ -> warn id 2206 $+ if shellType params == Ksh+ then "Quote to prevent word splitting/globbing, or split robustly with read -A or while read."+ else "Quote to prevent word splitting/globbing, or split robustly with mapfile or read -a."+ _ -> return ()++ forCommand id =+ warn id 2207 $+ if shellType params == Ksh+ then "Prefer read -A or while read to split command output (or quote to avoid splitting)."+ else "Prefer mapfile or read -a to split command output (or quote to avoid splitting)."+++prop_checkRedirectionToNumber1 = verify checkRedirectionToNumber "( 1 > 2 )"+prop_checkRedirectionToNumber2 = verify checkRedirectionToNumber "foo 1>2"+prop_checkRedirectionToNumber3 = verifyNot checkRedirectionToNumber "echo foo > '2'"+prop_checkRedirectionToNumber4 = verifyNot checkRedirectionToNumber "foo 1>&2"+checkRedirectionToNumber _ t = case t of+ T_IoFile id _ word -> sequence_ $ do+ file <- getUnquotedLiteral word+ guard $ all isDigit file+ return $ warn id 2210 "This is a file redirection. Was it supposed to be a comparison or fd operation?"+ _ -> return ()++prop_checkGlobAsCommand1 = verify checkGlobAsCommand "foo*"+prop_checkGlobAsCommand2 = verify checkGlobAsCommand "$(var[i])"+prop_checkGlobAsCommand3 = verifyNot checkGlobAsCommand "echo foo*"+checkGlobAsCommand _ t = case t of+ T_SimpleCommand _ _ (first:_)+ | isGlob first ->+ warn (getId first) 2211 "This is a glob used as a command name. Was it supposed to be in ${..}, array, or is it missing quoting?"+ _ -> return ()+++prop_checkFlagAsCommand1 = verify checkFlagAsCommand "-e file"+prop_checkFlagAsCommand2 = verify checkFlagAsCommand "foo\n --bar=baz"+prop_checkFlagAsCommand3 = verifyNot checkFlagAsCommand "'--myexec--' args"+prop_checkFlagAsCommand4 = verifyNot checkFlagAsCommand "var=cmd --arg" -- Handled by SC2037+checkFlagAsCommand _ t = case t of+ T_SimpleCommand _ [] (first:_)+ | isUnquotedFlag first ->+ warn (getId first) 2215 "This flag is used as a command name. Bad line break or missing [ .. ]?"+ _ -> return ()+++prop_checkEmptyCondition1 = verify checkEmptyCondition "if [ ]; then ..; fi"+prop_checkEmptyCondition2 = verifyNot checkEmptyCondition "[ foo -o bar ]"+checkEmptyCondition _ t = case t of+ TC_Empty id _ -> style id 2212 "Use 'false' instead of empty [/[[ conditionals."+ _ -> return ()++prop_checkPipeToNowhere1 = verify checkPipeToNowhere "foo | echo bar"+prop_checkPipeToNowhere2 = verify checkPipeToNowhere "basename < file.txt"+prop_checkPipeToNowhere3 = verify checkPipeToNowhere "printf 'Lol' <<< str"+prop_checkPipeToNowhere4 = verify checkPipeToNowhere "printf 'Lol' << eof\nlol\neof\n"+prop_checkPipeToNowhere5 = verifyNot checkPipeToNowhere "echo foo | xargs du"+prop_checkPipeToNowhere6 = verifyNot checkPipeToNowhere "ls | echo $(cat)"+prop_checkPipeToNowhere7 = verifyNot checkPipeToNowhere "echo foo | var=$(cat) ls"+prop_checkPipeToNowhere9 = verifyNot checkPipeToNowhere "mv -i f . < /dev/stdin"+prop_checkPipeToNowhere10 = verify checkPipeToNowhere "ls > file | grep foo"+prop_checkPipeToNowhere11 = verify checkPipeToNowhere "ls | grep foo < file"+prop_checkPipeToNowhere12 = verify checkPipeToNowhere "ls > foo > bar"+prop_checkPipeToNowhere13 = verify checkPipeToNowhere "ls > foo 2> bar > baz"+prop_checkPipeToNowhere14 = verify checkPipeToNowhere "ls > foo &> bar"+prop_checkPipeToNowhere15 = verifyNot checkPipeToNowhere "ls > foo 2> bar |& grep 'No space left'"+prop_checkPipeToNowhere16 = verifyNot checkPipeToNowhere "echo World | cat << EOF\nhello $(cat)\nEOF\n"+prop_checkPipeToNowhere17 = verify checkPipeToNowhere "echo World | cat << 'EOF'\nhello $(cat)\nEOF\n"+prop_checkPipeToNowhere18 = verifyNot checkPipeToNowhere "ls 1>&3 3>&1 3>&- | wc -l"+prop_checkPipeToNowhere19 = verifyNot checkPipeToNowhere "find . -print0 | du --files0-from=/dev/stdin"+prop_checkPipeToNowhere20 = verifyNot checkPipeToNowhere "find . | du --exclude-from=/dev/fd/0"+prop_checkPipeToNowhere21 = verifyNot checkPipeToNowhere "yes | cp -ri foo/* bar"+prop_checkPipeToNowhere22 = verifyNot checkPipeToNowhere "yes | rm --interactive *"++data PipeType = StdoutPipe | StdoutStderrPipe | NoPipe deriving (Eq)+checkPipeToNowhere :: Parameters -> Token -> WriterT [TokenComment] Identity ()+checkPipeToNowhere params t =+ case t of+ T_Pipeline _ pipes cmds ->+ mapM_ checkPipe $ commandsWithContext pipes cmds+ T_Redirecting _ redirects cmd | any redirectsStdin redirects -> checkRedir cmd+ _ -> return ()+ where+ checkPipe (input, stage, output) = do+ let hasConsumers = hasAdditionalConsumers stage+ let hasProducers = hasAdditionalProducers stage++ sequence_ $ do+ cmd <- getCommand stage+ name <- getCommandBasename cmd+ guard $ name `elem` nonReadingCommands+ guard $ not hasConsumers && input /= NoPipe+ guard . not $ commandSpecificException name cmd++ -- Confusing echo for cat is so common that it's worth a special case+ let suggestion =+ if name == "echo"+ then "Did you want 'cat' instead?"+ else "Wrong command or missing xargs?"+ return $ warn (getId cmd) 2216 $+ "Piping to '" ++ name ++ "', a command that doesn't read stdin. " ++ suggestion++ sequence_ $ do+ T_Redirecting _ redirs cmd <- return stage+ fds <- mapM getRedirectionFds redirs++ let fdAndToken :: [(Integer, Token)]+ fdAndToken =+ concatMap (\(list, redir) -> map (\n -> (n, redir)) list) $+ zip fds redirs++ let fdMap =+ Map.fromListWith (++) $+ map (\(a,b) -> (a,[b])) fdAndToken++ let inputWarning = sequence_ $ do+ guard $ input /= NoPipe && not hasConsumers+ (override:_) <- Map.lookup 0 fdMap+ return $ err (getOpId override) 2259 $+ "This redirection overrides piped input. To use both, merge or pass filenames."++ -- Only produce output warnings for regular pipes, since these are+ -- way more common, and `foo > out 2> err |& foo` can still write+ -- to stderr if the files fail to open+ let outputWarning = sequence_ $ do+ guard $ output == StdoutPipe && not hasProducers+ (override:_) <- Map.lookup 1 fdMap+ return $ err (getOpId override) 2260 $+ "This redirection overrides the output pipe. Use 'tee' to output to both."++ return $ do+ inputWarning+ outputWarning+ mapM_ warnAboutDupes $ Map.assocs fdMap++ commandSpecificException name cmd =+ case name of+ "du" -> any ((`elem` ["exclude-from", "files0-from"]) . snd) $ getAllFlags cmd+ _ | name `elem` interactiveFlagCmds -> hasInteractiveFlag cmd+ _ -> False++ warnAboutDupes (n, list@(_:_:_)) =+ forM_ list $ \c -> err (getOpId c) 2261 $+ "Multiple redirections compete for " ++ str n ++ ". Use cat, tee, or pass filenames instead."+ warnAboutDupes _ = return ()++ alternative =+ if shellType params `elem` [Bash, Ksh]+ then "process substitutions or temp files"+ else "temporary files"++ str n =+ case n of+ 0 -> "stdin"+ 1 -> "stdout"+ 2 -> "stderr"+ _ -> "FD " ++ show n++ checkRedir cmd = sequence_ $ do+ name <- getCommandBasename cmd+ guard $ name `elem` nonReadingCommands+ guard . not $ hasAdditionalConsumers cmd+ guard . not $ name `elem` interactiveFlagCmds && hasInteractiveFlag cmd+ let suggestion =+ if name == "echo"+ then "Did you want 'cat' instead?"+ else "Bad quoting, wrong command or missing xargs?"+ return $ warn (getId cmd) 2217 $+ "Redirecting to '" ++ name ++ "', a command that doesn't read stdin. " ++ suggestion++ -- Could any words in a SimpleCommand consume stdin (e.g. echo "$(cat)")?+ hasAdditionalConsumers = treeContains mayConsume+ -- Could any words in a SimpleCommand produce stdout? E.g. >(tee foo)+ hasAdditionalProducers = treeContains mayProduce+ treeContains pred t = isNothing $+ doAnalysis (guard . not . pred) t++ interactiveFlagCmds = [ "cp", "mv", "rm" ]+ hasInteractiveFlag cmd = cmd `hasFlag` "i" || cmd `hasFlag` "interactive"++ mayConsume t =+ case t of+ T_ProcSub _ "<" _ -> True+ T_Backticked {} -> True+ T_DollarExpansion {} -> True+ _ -> False++ mayProduce t =+ case t of+ T_ProcSub _ ">" _ -> True+ _ -> False++ getOpId t =+ case t of+ T_FdRedirect _ _ x -> getOpId x+ T_IoFile _ op _ -> getId op+ _ -> getId t++ getRedirectionFds t =+ case t of+ T_FdRedirect _ "" x -> getDefaultFds x+ T_FdRedirect _ "&" _ -> return [1, 2]+ T_FdRedirect _ num x | all isDigit num ->+ -- Don't report the number unless we know what it is.+ -- This avoids triggering on 3>&1 1>&3+ getDefaultFds x *> return [read num]+ -- Don't bother with {fd}>42 and such+ _ -> Nothing++ getDefaultFds redir =+ case redir of+ T_HereDoc {} -> return [0]+ T_HereString {} -> return [0]+ T_IoFile _ op _ ->+ case op of+ T_Less {} -> return [0]+ T_Greater {} -> return [1]+ T_DGREAT {} -> return [1]+ T_GREATAND {} -> return [1, 2]+ T_CLOBBER {} -> return [1]+ T_IoDuplicate _ op "-" -> getDefaultFds op+ _ -> Nothing+ _ -> Nothing++ redirectsStdin t =+ fromMaybe False $ do+ fds <- getRedirectionFds t+ return $ 0 `elem` fds++ pipeType t =+ case t of+ T_Pipe _ "|" -> StdoutPipe+ T_Pipe _ "|&" -> StdoutStderrPipe+ _ -> NoPipe++ commandsWithContext pipes cmds =+ let pipeTypes = map pipeType pipes+ inputs = NoPipe : pipeTypes+ outputs = pipeTypes ++ [NoPipe]+ in+ zip3 inputs cmds outputs++prop_checkUseBeforeDefinition1 = verifyTree checkUseBeforeDefinition "f; f() { true; }"+prop_checkUseBeforeDefinition2 = verifyNotTree checkUseBeforeDefinition "f() { true; }; f"+prop_checkUseBeforeDefinition3 = verifyNotTree checkUseBeforeDefinition "if ! mycmd --version; then mycmd() { true; }; fi"+prop_checkUseBeforeDefinition4 = verifyNotTree checkUseBeforeDefinition "mycmd || mycmd() { f; }"+prop_checkUseBeforeDefinition5 = verifyTree checkUseBeforeDefinition "false || mycmd; mycmd() { f; }"+prop_checkUseBeforeDefinition6 = verifyNotTree checkUseBeforeDefinition "f() { one; }; f; f() { two; }; f"+prop_checkUseBeforeDefinition7 = verifyNotTree checkUseBeforeDefinition "f() { true; }\nreturn\necho \"$(f)\"\necho \"$(f)\""+prop_checkUseBeforeDefinition8 = verifyNotTree checkUseBeforeDefinition "#!/usr/bin/env bats\n@test 'foo' { f; }\nf() { true; }"+prop_checkUseBeforeDefinition9 = verifyNotTree checkUseBeforeDefinition "#!/usr/bin/env bats\n@test 'foo' { f; }\nsetup() { f() { true; }; }"+prop_checkUseBeforeDefinition10 = verifyTree checkUseBeforeDefinition "#!/usr/bin/env bats\n@test 'foo' {\n f\n f() { true; }\n}"+prop_checkUseBeforeDefinition11 = verifyTree checkUseBeforeDefinition "#!/usr/bin/env bats\nf\n@test 'foo' { true; }\nf() { true; }"+prop_checkUseBeforeDefinition12 = verifyNotTree checkUseBeforeDefinition "setup() { f() { true; }; }; f; f() { true; }"+prop_checkUseBeforeDefinition13 = verifyNotTree checkUseBeforeDefinition "#!/usr/bin/env bats\nsetup() { f() { true; }; }\n@test \"a\" {\n f\n}\n@test \"b\" {\n f() { true; }\n}"+checkUseBeforeDefinition :: Parameters -> Token -> [TokenComment]+checkUseBeforeDefinition params t = fromMaybe [] $ do+ cfga <- cfgAnalysis params+ let funcs = execState (doAnalysis findFunction t) Map.empty+ -- Green cut: no point enumerating commands if there are no functions.+ guard . not $ Map.null funcs+ return $ execWriter $ doAnalysis (findInvocation cfga funcs) t+ where+ findFunction t =+ case t of+ T_Function id _ _ name _ -> modify (Map.insertWith (++) name [(id, isInBatsTest t)])+ _ -> return ()++ isInBatsTest t = any isBatsTest $ getPath (parentMap params) t+ isBatsTest t = case t of T_BatsTest {} -> True; _ -> False++ findInvocation cfga funcs t =+ case t of+ T_SimpleCommand id _ (cmd:_) -> sequence_ $ do+ name <- getLiteralString cmd+ definitions <- Map.lookup name funcs+ let invocations = map fst definitions+ -- Bats loads the whole file before running a test, so functions+ -- defined outside of tests are available in all of them.+ guard . not $ isInBatsTest t && any (not . snd) definitions+ -- Is the function definitely being defined later?+ -- Every definition has to be later: one whose order we can't+ -- determine, such as in a function nothing visibly invokes,+ -- may already have run.+ guard $ all (\c -> CF.doesPostDominate cfga c id) invocations+ -- Was one already defined, so it's actually a re-definition?+ guard . not $ any (\c -> CF.doesPostDominate cfga id c) invocations+ return $ err id 2218 "This function is only defined later. Move the definition up."+ _ -> return ()++prop_checkForLoopGlobVariables1 = verify checkForLoopGlobVariables "for i in $var/*.txt; do true; done"+prop_checkForLoopGlobVariables2 = verifyNot checkForLoopGlobVariables "for i in \"$var\"/*.txt; do true; done"+prop_checkForLoopGlobVariables3 = verifyNot checkForLoopGlobVariables "for i in $var; do true; done"+checkForLoopGlobVariables _ t =+ case t of+ T_ForIn _ _ words _ -> mapM_ check words+ _ -> return ()+ where+ check (T_NormalWord _ parts) =+ when (any isGlob parts) $+ mapM_ suggest $ filter isQuoteableExpansion parts+ suggest t = info (getId t) 2231+ "Quote expansions in this for loop glob to prevent wordsplitting, e.g. \"$dir\"/*.txt ."+++prop_checkSubshelledTests1 = verify checkSubshelledTests "a && ( [ b ] || ! [ c ] )"+prop_checkSubshelledTests2 = verify checkSubshelledTests "( [ a ] )"+prop_checkSubshelledTests3 = verify checkSubshelledTests "( [ a ] && [ b ] || test c )"+prop_checkSubshelledTests4 = verify checkSubshelledTests "( [ a ] && { [ b ] && [ c ]; } )"+prop_checkSubshelledTests5 = verifyNot checkSubshelledTests "( [[ ${var:=x} = y ]] )"+prop_checkSubshelledTests6 = verifyNot checkSubshelledTests "( [[ $((i++)) = 10 ]] )"+prop_checkSubshelledTests7 = verifyNot checkSubshelledTests "( [[ $((i+=1)) = 10 ]] )"+prop_checkSubshelledTests8 = verify checkSubshelledTests "# shellcheck disable=SC2234\nf() ( [[ x ]] )"++checkSubshelledTests params t =+ case t of+ T_Subshell id list | all isTestStructure list && (not (hasAssignment t)) ->+ case () of+ -- Special case for if (test) and while (test)+ _ | isCompoundCondition (getPath (parentMap params) t) ->+ style id 2233 "Remove superfluous (..) around condition to avoid subshell overhead."++ -- Special case for ([ x ]), except for func() ( [ x ] )+ _ | isSingleTest list && (not $ isFunctionBody (getPath (parentMap params) t)) ->+ style id 2234 "Remove superfluous (..) around test command to avoid subshell overhead."++ -- General case for ([ x ] || [ y ] && etc)+ _ -> style id 2235 "Use { ..; } instead of (..) to avoid subshell overhead."+ _ -> return ()+ where++ isSingleTest cmds =+ case cmds of+ [c] | isTestCommand c -> True+ _ -> False++ isFunctionBody path =+ case path of+ (_ NE.:| f:_) -> isFunction f+ _ -> False++ isTestStructure t =+ case t of+ T_Banged _ t -> isTestStructure t+ T_AndIf _ a b -> isTestStructure a && isTestStructure b+ T_OrIf _ a b -> isTestStructure a && isTestStructure b+ T_Pipeline _ [] [T_Redirecting _ _ cmd] ->+ case cmd of+ T_BraceGroup _ ts -> all isTestStructure ts+ T_Subshell _ ts -> all isTestStructure ts+ _ -> isTestCommand t+ _ -> isTestCommand t++ isTestCommand t =+ case t of+ T_Pipeline _ [] [T_Redirecting _ _ cmd] ->+ case cmd of+ T_Condition {} -> True+ _ -> cmd `isCommand` "test"+ _ -> False++ -- Check if a T_Subshell is used as a condition, e.g. if ( test )+ -- This technically also triggers for `if true; then ( test ); fi`+ -- but it's still a valid suggestion.+ isCompoundCondition chain =+ case dropWhile skippable (NE.tail chain) of+ T_IfExpression {} : _ -> True+ T_WhileExpression {} : _ -> True+ T_UntilExpression {} : _ -> True+ _ -> False++ hasAssignment t = isNothing $ doAnalysis guardNotAssignment t+ guardNotAssignment t =+ case t of+ TA_Assignment {} -> Nothing+ TA_Unary _ s _ -> guard . not $ "++" `isInfixOf` s || "--" `isInfixOf` s+ T_DollarBraced _ _ l ->+ let str = concat $ oversimplify l+ modifier = getBracedModifier str+ in+ guard . not $ "=" `isPrefixOf` modifier || ":=" `isPrefixOf` modifier+ T_DollarBraceCommandExpansion {} -> Nothing+ _ -> Just ()++ -- Skip any parent of a T_Subshell until we reach something interesting+ skippable t =+ case t of+ T_Redirecting _ [] _ -> True+ T_Pipeline _ [] _ -> True+ T_Annotation {} -> True+ _ -> False++prop_checkUnnecessarilyInvertedTest1 = verify checkUnnecessarilyInvertedTest "[ ! -z $var ]"+prop_checkUnnecessarilyInvertedTest2 = verify checkUnnecessarilyInvertedTest "! [[ -n $var ]]"+prop_checkUnnecessarilyInvertedTest3 = verifyNot checkUnnecessarilyInvertedTest "! [ -x $var ]"+prop_checkUnnecessarilyInvertedTest4 = verifyNot checkUnnecessarilyInvertedTest "[[ ! -w $var ]]"+prop_checkUnnecessarilyInvertedTest5 = verifyNot checkUnnecessarilyInvertedTest "[ -z $var ]"+prop_checkUnnecessarilyInvertedTest6 = verify checkUnnecessarilyInvertedTest "! [ $var != foo ]"+prop_checkUnnecessarilyInvertedTest7 = verify checkUnnecessarilyInvertedTest "[[ ! $var == foo ]]"+prop_checkUnnecessarilyInvertedTest8 = verifyNot checkUnnecessarilyInvertedTest "! [[ $var =~ .* ]]"+prop_checkUnnecessarilyInvertedTest9 = verify checkUnnecessarilyInvertedTest "[ ! $var -eq 0 ]"+prop_checkUnnecessarilyInvertedTest10 = verify checkUnnecessarilyInvertedTest "! [[ $var -gt 3 ]]"+prop_checkUnnecessarilyInvertedTest11 = verify checkUnnecessarilyInvertedTest "test ! -n \"$1\""+prop_checkUnnecessarilyInvertedTest12 = verify checkUnnecessarilyInvertedTest "! test -z \"$1\""+prop_checkUnnecessarilyInvertedTest13 = verifyNot checkUnnecessarilyInvertedTest "test ! -x \"$1\""+prop_checkUnnecessarilyInvertedTest14 = verifyNot checkUnnecessarilyInvertedTest "test -n \"$1\""+prop_checkUnnecessarilyInvertedTest15 = verifyNot checkUnnecessarilyInvertedTest "! test -x \"$1\""+checkUnnecessarilyInvertedTest _ t =+ case t of+ TC_Unary _ _ "!" (TC_Unary _ _ op _) ->+ case op of+ "-n" -> style (getId t) 2236 "Use -z instead of ! -n."+ "-z" -> style (getId t) 2236 "Use -n instead of ! -z."+ _ -> return ()+ T_Banged _ (T_Pipeline _ _+ [T_Redirecting _ _ (T_Condition _ _ _ (TC_Unary _ _ op _))]) ->+ case op of+ "-n" -> style (getId t) 2237 "Use [ -z .. ] instead of ! [ -n .. ]."+ "-z" -> style (getId t) 2237 "Use [ -n .. ] instead of ! [ -z .. ]."+ _ -> return ()+ -- test ! -n x+ T_SimpleCommand _ _ [_, bang, op, _]+ | t `isCommand` "test" && getLiteralString bang == Just "!" ->+ case getLiteralString op of+ Just "-n" -> style (getId t) 2236 "Use -z instead of ! -n."+ Just "-z" -> style (getId t) 2236 "Use -n instead of ! -z."+ _ -> return ()+ -- ! test -z x+ T_Banged _ (T_Pipeline _ _+ [T_Redirecting _ _ s@(T_SimpleCommand _ _ [_, op, _])])+ | s `isCommand` "test" ->+ case getLiteralString op of+ Just "-n" -> style (getId t) 2237 "Use test -z .. instead of ! test -n .."+ Just "-z" -> style (getId t) 2237 "Use test -n .. instead of ! test -z .."+ _ -> return ()+ TC_Unary _ _ "!" (TC_Binary _ bracketStyle op _ _) ->+ maybeSuggestRewrite True bracketStyle (getId t) op+ T_Banged _ (T_Pipeline _ _+ [T_Redirecting _ _ (T_Condition _ _ _ (TC_Binary _ bracketStyle op _ _))]) ->+ maybeSuggestRewrite False bracketStyle (getId t) op+ _ -> return ()+ where+ inversionMap = Map.fromList [+ ("=", "!="),+ ("==", "!="),+ ("!=", "="),+ ("-eq", "-ne"),+ ("-ne", "-eq"),+ ("-le", "-gt"),+ ("-gt", "-le"),+ ("-ge", "-lt"),+ ("-lt", "-ge")+ ]+ maybeSuggestRewrite bangInside bracketStyle id op = sequence_ $ do+ newOp <- Map.lookup op inversionMap+ let oldExpr = "a " ++ op ++ " b"+ let newExpr = "a " ++ newOp ++ " b"+ let bracket s = if bracketStyle == SingleBracket then "[ " ++ s ++ " ]" else "[[ " ++ s ++ " ]]"+ return $+ if bangInside+ then style id 2335 $ "Use " ++ newExpr ++ " instead of ! " ++ oldExpr ++ "."+ else style id 2335 $ "Use " ++ (bracket newExpr) ++ " instead of ! " ++ (bracket oldExpr) ++ "."+++prop_checkRedirectionToCommand1 = verify checkRedirectionToCommand "ls > rm"+prop_checkRedirectionToCommand2 = verifyNot checkRedirectionToCommand "ls > 'rm'"+prop_checkRedirectionToCommand3 = verifyNot checkRedirectionToCommand "ls > myfile"+checkRedirectionToCommand _ t =+ case t of+ T_IoFile _ _ (T_NormalWord id [T_Literal _ str]) | str `elem` commonCommands+ && str /= "file" -> -- This would be confusing+ warn id 2238 "Redirecting to/from command name instead of file. Did you want pipes/xargs (or quote to ignore)?"+ _ -> return ()++prop_checkNullaryExpansionTest1 = verify checkNullaryExpansionTest "[[ $(a) ]]"+prop_checkNullaryExpansionTest2 = verify checkNullaryExpansionTest "[[ $a ]]"+prop_checkNullaryExpansionTest3 = verifyNot checkNullaryExpansionTest "[[ $a=1 ]]"+prop_checkNullaryExpansionTest4 = verifyNot checkNullaryExpansionTest "[[ -n $(a) ]]"+prop_checkNullaryExpansionTest5 = verify checkNullaryExpansionTest "[[ \"$a$b\" ]]"+prop_checkNullaryExpansionTest6 = verify checkNullaryExpansionTest "[[ `x` ]]"+checkNullaryExpansionTest params t =+ case t of+ TC_Nullary _ _ word ->+ case getWordParts word of+ [t] | isCommandSubstitution t ->+ styleWithFix id 2243 "Prefer explicit -n to check for output (or run command without [/[[ to check for success)." fix++ -- If they're constant, you get SC2157 &co+ x | all (not . isConstant) x ->+ styleWithFix id 2244 "Prefer explicit -n to check non-empty string (or use =/-ne to check boolean/integer)." fix+ _ -> return ()+ where+ id = getId word+ fix = fixWith [replaceStart id params 0 "-n "]+ _ -> return ()+++prop_checkDollarQuoteParen1 = verify checkDollarQuoteParen "$\"(foo)\""+prop_checkDollarQuoteParen2 = verify checkDollarQuoteParen "$\"{foo}\""+prop_checkDollarQuoteParen3 = verifyNot checkDollarQuoteParen "\"$(foo)\""+prop_checkDollarQuoteParen4 = verifyNot checkDollarQuoteParen "$\"..\""+checkDollarQuoteParen params t =+ case t of+ T_DollarDoubleQuoted id ((T_Literal _ (c:_)):_) | c `elem` "({" ->+ warnWithFix id 2247 "Flip leading $ and \" if this should be a quoted substitution." (fix id)+ _ -> return ()+ where+ fix id = fixWith [replaceStart id params 2 "\"$"]++prop_checkTranslatedStringVariable1 = verify checkTranslatedStringVariable "foo_bar2=val; $\"foo_bar2\""+prop_checkTranslatedStringVariable2 = verifyNot checkTranslatedStringVariable "$\"foo_bar2\""+prop_checkTranslatedStringVariable3 = verifyNot checkTranslatedStringVariable "$\"..\""+prop_checkTranslatedStringVariable4 = verifyNot checkTranslatedStringVariable "var=val; $\"$var\""+prop_checkTranslatedStringVariable5 = verifyNot checkTranslatedStringVariable "foo=var; bar=val2; $\"foo bar\""+checkTranslatedStringVariable params (T_DollarDoubleQuoted id [T_Literal _ s])+ | all isVariableChar s+ && S.member s assignments+ = warnWithFix id 2256 "This translated string is the name of a variable. Flip leading $ and \" if this should be a quoted substitution." (fix id)+ where+ assignments = S.fromList [name | Assignment (_, _, name, _) <- variableFlow params, isVariableName name]+ fix id = fixWith [replaceStart id params 2 "\"$"]+checkTranslatedStringVariable _ _ = return ()++prop_checkDefaultCase1 = verify checkDefaultCase "case $1 in a) true ;; esac"+prop_checkDefaultCase2 = verify checkDefaultCase "case $1 in ?*?) true ;; *? ) true ;; esac"+prop_checkDefaultCase3 = verifyNot checkDefaultCase "case $1 in x|*) true ;; esac"+prop_checkDefaultCase4 = verifyNot checkDefaultCase "case $1 in **) true ;; esac"+checkDefaultCase _ t =+ case t of+ T_CaseExpression id _ list ->+ unless (any canMatchAny list) $+ info id 2249 "Consider adding a default *) case, even if it just exits with error."+ _ -> return ()+ where+ canMatchAny (_, list, _) = any canMatchAny' list+ -- hlint objects to 'pattern' as a variable name+ canMatchAny' pat = fromMaybe False $ do+ pg <- wordToExactPseudoGlob pat+ return $ pseudoGlobIsSuperSetof pg [PGMany]++prop_checkUselessBang1 = verify checkUselessBang "set -e; ! true; rest"+prop_checkUselessBang2 = verifyNot checkUselessBang "! true; rest"+prop_checkUselessBang3 = verify checkUselessBang "set -e; while true; do ! true; done"+prop_checkUselessBang4 = verifyNot checkUselessBang "set -e; if ! true; then true; fi"+prop_checkUselessBang5 = verifyNot checkUselessBang "set -e; ( ! true )"+prop_checkUselessBang6 = verify checkUselessBang "set -e; { ! true; }"+prop_checkUselessBang7 = verifyNot checkUselessBang "set -e; x() { ! [ x ]; }"+prop_checkUselessBang8 = verifyNot checkUselessBang "set -e; if { ! true; }; then true; fi"+prop_checkUselessBang9 = verifyNot checkUselessBang "set -e; while ! true; do true; done"+prop_checkUselessBang10 = verify checkUselessBang "set -e\nshellcheck disable=SC0000\n! true\nrest"+checkUselessBang params t = when (hasErrexit params) $ mapM_ check (getNonReturningCommands t)+ where+ check t =+ case t of+ T_Banged id cmd | not $ isCondition (getPath (parentMap params) t) ->+ addComment $ makeCommentWithFix InfoC id 2251+ "This ! is not on a condition and skips errexit. Use `&& exit 1` instead, or make sure $? is checked."+ (fixWith [replaceStart id params 1 "", replaceEnd (getId cmd) params 0 " && exit 1"])+ T_Annotation _ _ t -> check t+ _ -> return ()++ -- Get all the subcommands that aren't likely to be the return value+ getNonReturningCommands :: Token -> [Token]+ getNonReturningCommands t =+ case t of+ T_Script _ _ list -> dropLast list+ T_BraceGroup _ list -> if isFunctionBody t then dropLast list else list+ T_Subshell _ list -> dropLast list+ T_WhileExpression _ conds cmds -> dropLast conds ++ cmds+ T_UntilExpression _ conds cmds -> dropLast conds ++ cmds+ T_ForIn _ _ _ list -> list+ T_ForArithmetic _ _ _ _ list -> list+ T_Annotation _ _ t -> getNonReturningCommands t+ T_IfExpression _ conds elses ->+ concatMap (dropLast . fst) conds ++ concatMap snd conds ++ elses+ _ -> []++ isFunctionBody t =+ case getPath (parentMap params) t of+ _ NE.:| T_Function {}:_-> True+ _ -> False++ dropLast t =+ case t of+ [_] -> []+ x:rest -> x : dropLast rest+ _ -> []++prop_checkModifiedArithmeticInRedirection1 = verify checkModifiedArithmeticInRedirection "ls > $((i++))"+prop_checkModifiedArithmeticInRedirection2 = verify checkModifiedArithmeticInRedirection "cat < \"foo$((i++)).txt\""+prop_checkModifiedArithmeticInRedirection3 = verifyNot checkModifiedArithmeticInRedirection "while true; do true; done > $((i++))"+prop_checkModifiedArithmeticInRedirection4 = verify checkModifiedArithmeticInRedirection "cat <<< $((i++))"+prop_checkModifiedArithmeticInRedirection5 = verify checkModifiedArithmeticInRedirection "cat << foo\n$((i++))\nfoo\n"+prop_checkModifiedArithmeticInRedirection6 = verifyNot checkModifiedArithmeticInRedirection "#!/bin/dash\nls > $((i=i+1))"+prop_checkModifiedArithmeticInRedirection7 = verifyNot checkModifiedArithmeticInRedirection "#!/bin/busybox sh\ncat << foo\n$((i++))\nfoo\n"+checkModifiedArithmeticInRedirection params t = unless (shellType params == Dash || shellType params == BusyboxSh) $+ case t of+ T_Redirecting _ redirs (T_SimpleCommand _ _ (_:_)) -> mapM_ checkRedirs redirs+ _ -> return ()+ where+ checkRedirs t =+ case t of+ T_FdRedirect _ _ (T_IoFile _ _ word) ->+ mapM_ checkArithmetic $ getWordParts word+ T_FdRedirect _ _ (T_HereString _ word) ->+ mapM_ checkArithmetic $ getWordParts word+ T_FdRedirect _ _ (T_HereDoc _ _ _ _ list) ->+ mapM_ checkArithmetic list+ _ -> return ()+ checkArithmetic t =+ case t of+ T_DollarArithmetic _ x -> checkModifying x+ _ -> return ()+ checkModifying t =+ case t of+ TA_Sequence _ list -> mapM_ checkModifying list+ TA_Unary id s _ | s `elem` ["|++", "++|", "|--", "--|"] -> warnFor id+ TA_Assignment id _ _ _ -> warnFor id+ TA_Binary _ _ x y -> mapM_ checkModifying [x ,y]+ TA_Trinary _ x y z -> mapM_ checkModifying [x, y, z]+ _ -> return ()+ warnFor id =+ warn id 2257 "Arithmetic modifications in command redirections may be discarded. Do them separately."++prop_checkAliasUsedInSameParsingUnit1 = verifyTree checkAliasUsedInSameParsingUnit "alias x=y; x"+prop_checkAliasUsedInSameParsingUnit2 = verifyNotTree checkAliasUsedInSameParsingUnit "alias x=y\nx"+prop_checkAliasUsedInSameParsingUnit3 = verifyTree checkAliasUsedInSameParsingUnit "{ alias x=y\nx\n}"+prop_checkAliasUsedInSameParsingUnit4 = verifyNotTree checkAliasUsedInSameParsingUnit "alias x=y; 'x';"+prop_checkAliasUsedInSameParsingUnit5 = verifyNotTree checkAliasUsedInSameParsingUnit ":\n{\n#shellcheck disable=SC2262\nalias x=y\nx\n}"+prop_checkAliasUsedInSameParsingUnit6 = verifyNotTree checkAliasUsedInSameParsingUnit ":\n{\n#shellcheck disable=SC2262\nalias x=y\nalias x=z\nx\n}" -- Only consider the first instance+checkAliasUsedInSameParsingUnit :: Parameters -> Token -> [TokenComment]+checkAliasUsedInSameParsingUnit params root =+ let+ -- Get all root commands+ commands = concat $ getCommandSequences root+ -- Group them by whether they start on the same line where the previous one ended+ units = groupByLink followsOnLine commands+ in+ execWriter $ mapM_ checkUnit units+ where+ lineSpan t =+ let m = tokenPositions params in do+ (start, end) <- Map.lookup t m+ return $ (posLine start, posLine end)++ followsOnLine a b = fromMaybe False $ do+ (_, end) <- lineSpan (getId a)+ (start, _) <- lineSpan (getId b)+ return $ end == start++ checkUnit :: [Token] -> Writer [TokenComment] ()+ checkUnit unit = evalStateT (mapM_ (doAnalysis findCommands) unit) (Map.empty)++ findCommands :: Token -> StateT (Map.Map String Token) (Writer [TokenComment]) ()+ findCommands t = case t of+ T_SimpleCommand _ _ (cmd:args) ->+ case getUnquotedLiteral cmd of+ Just "alias" ->+ mapM_ addAlias args+ Just name | '/' `notElem` name -> do+ cmd <- gets (Map.lookup name)+ case cmd of+ Just alias ->+ unless (isSourced params t || shouldIgnoreCode params 2262 alias) $ do+ warn (getId alias) 2262 "This alias can't be defined and used in the same parsing unit. Use a function instead."+ info (getId t) 2263 "Since they're in the same parsing unit, this command will not refer to the previously mentioned alias."+ _ -> return ()+ _ -> return ()+ _ -> return ()+ addAlias arg = do+ let (name, value) = break (== '=') $ getLiteralStringDef "-" arg+ when (isVariableName name && not (null value)) $+ modify (Map.insertWith (\new old -> old) name arg)++isSourced params t =+ let+ f (T_SourceCommand {}) = True+ f _ = False+ in+ any f $ getPath (parentMap params) t+++-- Like groupBy, but compares pairs of adjacent elements, rather than against the first of the span+prop_groupByLink1 = groupByLink (\a b -> a+1 == b) [1,2,3,2,3,7,8,9] == [[1,2,3], [2,3], [7,8,9]]+prop_groupByLink2 = groupByLink (==) ([] :: [()]) == []+groupByLink :: (a -> a -> Bool) -> [a] -> [[a]]+groupByLink f list =+ case list of+ [] -> []+ (x:xs) -> foldr c n xs x []+ where+ c next rest current span =+ if f current next+ then rest next (current:span)+ else (reverse $ current:span) : rest next []+ n current span = [reverse (current:span)]+++prop_checkBlatantRecursion1 = verify checkBlatantRecursion ":(){ :|:& };:"+prop_checkBlatantRecursion2 = verify checkBlatantRecursion "f() { f; }"+prop_checkBlatantRecursion3 = verifyNot checkBlatantRecursion "f() { command f; }"+prop_checkBlatantRecursion4 = verify checkBlatantRecursion "cd() { cd \"$lol/$1\" || exit; }"+prop_checkBlatantRecursion5 = verifyNot checkBlatantRecursion "cd() { [ -z \"$1\" ] || cd \"$1\"; }"+prop_checkBlatantRecursion6 = verifyNot checkBlatantRecursion "cd() { something; cd $1; }"+prop_checkBlatantRecursion7 = verifyNot checkBlatantRecursion "cd() { builtin cd $1; }"+checkBlatantRecursion :: Parameters -> Token -> Writer [TokenComment] ()+checkBlatantRecursion params t =+ case t of+ T_Function _ _ _ name body ->+ case getCommandSequences body of+ [first : _] -> checkList name first+ _ -> return ()+ _ -> return ()+ where+ checkList :: String -> Token -> Writer [TokenComment] ()+ checkList name t =+ case t of+ T_Backgrounded _ t -> checkList name t+ T_KshCoprocess _ t -> checkList name t+ T_AndIf _ lhs _ -> checkList name lhs+ T_OrIf _ lhs _ -> checkList name lhs+ T_Pipeline _ _ cmds -> mapM_ (checkCommand name) cmds+ _ -> return ()++ checkCommand :: String -> Token -> Writer [TokenComment] ()+ checkCommand name cmd = sequence_ $ do+ let (invokedM, t) = getCommandNameAndToken True cmd+ invoked <- invokedM+ guard $ name == invoked+ return $+ errWithFix (getId t) 2264+ ("This function unconditionally re-invokes itself. Missing 'command'?")+ (fixWith [replaceStart (getId t) params 0 $ "command "])+++prop_checkBadTestAndOr1 = verify checkBadTestAndOr "[ x ] & [ y ]"+prop_checkBadTestAndOr2 = verify checkBadTestAndOr "test -e foo & [ y ]"+prop_checkBadTestAndOr3 = verify checkBadTestAndOr "[ x ] | [ y ]"+checkBadTestAndOr params t =+ case t of+ T_Pipeline _ seps cmds@(_:_:_) -> checkOrs seps cmds+ T_Backgrounded id cmd -> checkAnds id cmd+ _ -> return ()+ where+ checkOrs seps cmds =+ let maybeSeps = map Just seps+ commandWithSeps = zip3 (Nothing:maybeSeps) cmds (maybeSeps ++ [Nothing])+ in+ mapM_ checkTest commandWithSeps+ checkTest (before, cmd, after) =+ when (isTestCommand cmd) $ do+ checkPipe before+ checkPipe after++ checkPipe t =+ case t of+ Just (T_Pipe id "|") ->+ warnWithFix id 2266 "Use || for logical OR. Single | will pipe." $+ fixWith [replaceEnd id params 0 "|"]+ _ -> return ()++ checkAnds id t =+ case t of+ T_AndIf _ _ rhs -> checkAnds id rhs+ T_OrIf _ _ rhs -> checkAnds id rhs+ T_Pipeline _ _ list | not (null list) -> checkAnds id (last list)+ cmd -> when (isTestCommand cmd) $+ errWithFix id 2265 "Use && for logical AND. Single & will background and return true." $+ (fixWith [replaceEnd id params 0 "&"])+++prop_checkComparisonWithLeadingX1 = verify checkComparisonWithLeadingX "[ x$foo = xlol ]"+prop_checkComparisonWithLeadingX2 = verify checkComparisonWithLeadingX "test x$foo = xlol"+prop_checkComparisonWithLeadingX3 = verifyNot checkComparisonWithLeadingX "[ $foo = xbar ]"+prop_checkComparisonWithLeadingX4 = verifyNot checkComparisonWithLeadingX "test $foo = xbar"+prop_checkComparisonWithLeadingX5 = verify checkComparisonWithLeadingX "[ \"x$foo\" = 'xlol' ]"+prop_checkComparisonWithLeadingX6 = verify checkComparisonWithLeadingX "[ x\"$foo\" = x'lol' ]"+prop_checkComparisonWithLeadingX7 = verify checkComparisonWithLeadingX "[ X$foo != Xbar ]"+checkComparisonWithLeadingX params t =+ case t of+ TC_Binary id typ op lhs rhs+ | op `elem` ["=", "==", "!="] ->+ check lhs rhs+ T_SimpleCommand _ _ [cmd, lhs, op, rhs]+ | getLiteralString cmd == Just "test" &&+ getLiteralString op `elem` [Just "=", Just "==", Just "!="] ->+ check lhs rhs+ _ -> return ()+ where+ msg = "Avoid x-prefix in comparisons as it no longer serves a purpose."+ check lhs rhs = sequence_ $ do+ l <- fixLeadingX lhs+ r <- fixLeadingX rhs+ return $ styleWithFix (getId lhs) 2268 msg $ fixWith [l, r]++ fixLeadingX token =+ case getWordParts token of+ T_Literal id (c:_):_ | toLower c == 'x' ->+ case token of+ -- The side is a single, unquoted x or X, so we have to quote+ T_NormalWord _ [T_Literal id [c]] ->+ return $ replaceStart id params 1 "\"\""+ -- Otherwise we can just delete it+ _ -> return $ replaceStart id params 1 ""+ T_SingleQuoted id (c:rest):_ | toLower c == 'x' ->+ -- Replace the single quote and the character x or X+ return $ replaceStart id params 2 "'"+ _ -> Nothing+++prop_checkAssignToSelf1 = verify checkAssignToSelf "x=$x"+prop_checkAssignToSelf2 = verify checkAssignToSelf "x=${x}"+prop_checkAssignToSelf3 = verify checkAssignToSelf "x=\"$x\""+prop_checkAssignToSelf4 = verifyNot checkAssignToSelf "x=$x mycmd"+checkAssignToSelf _ t =+ case t of+ T_SimpleCommand _ vars [] -> mapM_ check vars+ _ -> return ()+ where+ check t =+ case t of+ T_Assignment id Assign name [] t ->+ case getWordParts t of+ [T_DollarBraced _ _ b] -> do+ when (Just name == getLiteralString b) $+ msg id+ _ -> return ()+ _ -> return ()+ msg id = info id 2269 "This variable is assigned to itself, so the assignment does nothing."+++prop_checkEqualsInCommand1a = verifyCodes checkEqualsInCommand [2277] "#!/bin/bash\n0='foo'"+prop_checkEqualsInCommand2a = verifyCodes checkEqualsInCommand [2278] "#!/bin/ksh \n$0='foo'"+prop_checkEqualsInCommand3a = verifyCodes checkEqualsInCommand [2279] "#!/bin/dash\n${0}='foo'"+prop_checkEqualsInCommand4a = verifyCodes checkEqualsInCommand [2280] "#!/bin/sh \n0='foo'"++prop_checkEqualsInCommand1b = verifyCodes checkEqualsInCommand [2270] "1='foo'"+prop_checkEqualsInCommand2b = verifyCodes checkEqualsInCommand [2270] "${2}='foo'"++prop_checkEqualsInCommand1c = verifyCodes checkEqualsInCommand [2271] "var$((n+1))=value"+prop_checkEqualsInCommand2c = verifyCodes checkEqualsInCommand [2271] "var${x}=value"+prop_checkEqualsInCommand3c = verifyCodes checkEqualsInCommand [2271] "var$((cmd))x='foo'"+prop_checkEqualsInCommand4c = verifyCodes checkEqualsInCommand [2271] "$(cmd)='foo'"++prop_checkEqualsInCommand1d = verifyCodes checkEqualsInCommand [2273] "======="+prop_checkEqualsInCommand2d = verifyCodes checkEqualsInCommand [2274] "======= Here ======="+prop_checkEqualsInCommand3d = verifyCodes checkEqualsInCommand [2275] "foo\n=42"++prop_checkEqualsInCommand1e = verifyCodes checkEqualsInCommand [] "--foo=bar"+prop_checkEqualsInCommand2e = verifyCodes checkEqualsInCommand [] "$(cmd)'=foo'"+prop_checkEqualsInCommand3e = verifyCodes checkEqualsInCommand [2276] "var${x}/=value"+prop_checkEqualsInCommand4e = verifyCodes checkEqualsInCommand [2276] "${}=value"+prop_checkEqualsInCommand5e = verifyCodes checkEqualsInCommand [2276] "${#x}=value"++prop_checkEqualsInCommand1f = verifyCodes checkEqualsInCommand [2281] "$var=foo"+prop_checkEqualsInCommand2f = verifyCodes checkEqualsInCommand [2281] "$a=$b"+prop_checkEqualsInCommand3f = verifyCodes checkEqualsInCommand [2281] "${var}=foo"+prop_checkEqualsInCommand4f = verifyCodes checkEqualsInCommand [2281] "${var[42]}=foo"+prop_checkEqualsInCommand5f = verifyCodes checkEqualsInCommand [2281] "$var+=foo"++prop_checkEqualsInCommand1g = verifyCodes checkEqualsInCommand [2282] "411toppm=true"++checkEqualsInCommand params originalToken =+ case originalToken of+ T_SimpleCommand _ _ (word:_) -> check word+ _ -> return ()+ where+ hasEquals t =+ case t of+ T_Literal _ s -> '=' `elem` s+ _ -> False++ check t@(T_NormalWord _ list) | any hasEquals list =+ case break hasEquals list of+ (leading, (eq:_)) -> msg t (stripSinglePlus leading) eq+ _ -> return ()+ check _ = return ()++ -- This is a workaround for the parser adding + and = as separate literals+ stripSinglePlus l =+ case reverse l of+ (T_Literal _ "+"):rest -> reverse rest+ _ -> l++ positionalAssignmentRe = mkRegex "^[0-9][0-9]?="+ positionalMsg id =+ err id 2270 "To assign positional parameters, use 'set -- first second ..' (or use [ ] to compare)."+ indirectionMsg id =+ err id 2271 "For indirection, use arrays, declare \"var$n=value\", or (for sh) read/eval."+ badComparisonMsg id =+ err id 2272 "Command name contains ==. For comparison, use [ \"$var\" = value ]."+ conflictMarkerMsg id =+ err id 2273 "Sequence of ===s found. Merge conflict or intended as a commented border?"+ borderMsg id =+ err id 2274 "Command name starts with ===. Intended as a commented border?"+ prefixMsg id =+ err id 2275 "Command name starts with =. Bad line break?"+ genericMsg id =+ err id 2276 "This is interpreted as a command name containing '='. Bad assignment or comparison?"+ assign0Msg id bashfix =+ case shellType params of+ Bash -> errWithFix id 2277 "Use BASH_ARGV0 to assign to $0 in bash (or use [ ] to compare)." bashfix+ Ksh -> err id 2278 "$0 can't be assigned in Ksh (but it does reflect the current function)."+ Dash -> err id 2279 "$0 can't be assigned in Dash. This becomes a command name."+ BusyboxSh -> err id 2279 "$0 can't be assigned in Busybox Ash. This becomes a command name."+ _ -> err id 2280 "$0 can't be assigned this way, and there is no portable alternative."+ leadingNumberMsg id =+ err id 2282 "Variable names can't start with numbers, so this is interpreted as a command."++ isExpansion t =+ case t of+ T_Arithmetic {} -> True+ _ -> isQuoteableExpansion t++ isConflictMarker cmd = fromMaybe False $ do+ str <- getUnquotedLiteral cmd+ guard $ all (== '=') str+ guard $ length str >= 4 && length str <= 12 -- Git uses 7 but who knows+ return True++ mayBeVariableName l = fromMaybe False $ do+ guard . not $ any isQuotes l+ guard . not $ any willBecomeMultipleArgs l+ str <- getLiteralStringExt (\_ -> Just "x") (T_NormalWord (Id 0) l)+ return $ isVariableName str++ isLeadingNumberVar s =+ case takeWhile (/= '=') s of+ lead@(x:_) -> isDigit x && all isVariableChar lead && not (all isDigit lead)+ [] -> False++ msg cmd leading (T_Literal litId s) = do+ -- There are many different cases, and the order of the branches matter.+ case leading of+ -- --foo=42+ [] | "-" `isPrefixOf` s -> -- There's SC2215 for these+ return ()++ -- ======Hello======+ [] | "=" `isPrefixOf` s ->+ case originalToken of+ T_SimpleCommand _ [] [word] | isConflictMarker word ->+ conflictMarkerMsg (getId originalToken)+ _ | "===" `isPrefixOf` s -> borderMsg (getId originalToken)+ _ -> prefixMsg (getId cmd)++ -- '$var==42'+ _ | "==" `isInfixOf` s ->+ badComparisonMsg (getId cmd)++ -- '${foo[x]}=42' and '$foo=42'+ [T_DollarBraced id braced l] | "=" `isPrefixOf` s -> do+ let variableStr = concat $ oversimplify l+ let variableReference = getBracedReference variableStr+ let variableModifier = getBracedModifier variableStr+ let isPlain = isVariableName variableStr+ let isPositional = all isDigit variableStr++ let isArray = variableReference /= ""+ && "[" `isPrefixOf` variableModifier+ && "]" `isSuffixOf` variableModifier++ case () of+ -- '$foo=bar' should already have caused a parse-time SC1066+ -- _ | not braced && isPlain ->+ -- return ()++ _ | variableStr == "" -> -- Don't try to fix ${}=foo+ genericMsg (getId cmd)++ -- '$#=42' or '${#var}=42'+ _ | "#" `isPrefixOf` variableStr ->+ genericMsg (getId cmd)++ -- '${0}=42'+ _ | variableStr == "0" ->+ assign0Msg id $ fixWith [replaceToken id params "BASH_ARGV0"]++ -- '$2=2'+ _ | isPositional ->+ positionalMsg id++ _ | isArray || isPlain ->+ errWithFix id 2281+ ("Don't use " ++ (if braced then "${}" else "$") ++ " on the left side of assignments.") $+ fixWith $+ if braced+ then [ replaceStart id params 2 "", replaceEnd id params 1 "" ]+ else [ replaceStart id params 1 "" ]++ _ -> indirectionMsg id++ -- 2=42+ [] | s `matches` positionalAssignmentRe ->+ if "0=" `isPrefixOf` s+ then+ assign0Msg litId $ fixWith [replaceStart litId params 1 "BASH_ARGV0"]+ else+ positionalMsg litId++ -- 9foo=42+ [] | isLeadingNumberVar s ->+ leadingNumberMsg (getId cmd)++ -- var${foo}x=42+ (_:_) | mayBeVariableName leading && (all isVariableChar $ takeWhile (/= '=') s) ->+ indirectionMsg (getId cmd)++ _ -> genericMsg (getId cmd)+++prop_checkSecondArgIsComparison1 = verify checkSecondArgIsComparison "foo = $bar"+prop_checkSecondArgIsComparison2 = verify checkSecondArgIsComparison "$foo = $bar"+prop_checkSecondArgIsComparison3 = verify checkSecondArgIsComparison "2f == $bar"+prop_checkSecondArgIsComparison4 = verify checkSecondArgIsComparison "'var' =$bar"+prop_checkSecondArgIsComparison5 = verify checkSecondArgIsComparison "foo ='$bar'"+prop_checkSecondArgIsComparison6 = verify checkSecondArgIsComparison "$foo =$bar"+prop_checkSecondArgIsComparison7 = verify checkSecondArgIsComparison "2f ==$bar"+prop_checkSecondArgIsComparison8 = verify checkSecondArgIsComparison "'var' =$bar"+prop_checkSecondArgIsComparison9 = verify checkSecondArgIsComparison "var += $(foo)"+prop_checkSecondArgIsComparison10 = verify checkSecondArgIsComparison "var +=$(foo)"+checkSecondArgIsComparison _ t =+ case t of+ T_SimpleCommand _ _ (lhs:arg:_) -> sequence_ $ do+ argString <- getLeadingUnquotedString arg+ case argString of+ '=':'=':'=':'=':_ -> Nothing -- Don't warn about `echo ======` and such+ '+':'=':_ ->+ return $ err (headId t) 2285 $+ "Remove spaces around += to assign (or quote '+=' if literal)."+ '=':'=':_ ->+ return $ err (getId t) 2284 $+ "Use [ x = y ] to compare values (or quote '==' if literal)."+ '=':_ ->+ return $ err (headId arg) 2283 $+ "Remove spaces around = to assign (or use [ ] to compare, or quote '=' if literal)."+ _ -> Nothing+ _ -> return ()+ where+ -- We don't pinpoint exactly, but this helps cases like foo =$bar+ headId t =+ case t of+ T_NormalWord _ (x:_) -> getId x+ _ -> getId t+++prop_checkCommandWithTrailingSymbol1 = verify checkCommandWithTrailingSymbol "/"+prop_checkCommandWithTrailingSymbol2 = verify checkCommandWithTrailingSymbol "/foo/ bar/baz"+prop_checkCommandWithTrailingSymbol3 = verify checkCommandWithTrailingSymbol "/"+prop_checkCommandWithTrailingSymbol4 = verifyNot checkCommandWithTrailingSymbol "/*"+prop_checkCommandWithTrailingSymbol5 = verifyNot checkCommandWithTrailingSymbol "$foo/$bar"+prop_checkCommandWithTrailingSymbol6 = verify checkCommandWithTrailingSymbol "foo, bar"+prop_checkCommandWithTrailingSymbol7 = verifyNot checkCommandWithTrailingSymbol ". foo.sh"+prop_checkCommandWithTrailingSymbol8 = verifyNot checkCommandWithTrailingSymbol ": foo"+prop_checkCommandWithTrailingSymbol9 = verifyNot checkCommandWithTrailingSymbol "/usr/bin/python[23] file.py"++checkCommandWithTrailingSymbol _ t =+ case t of+ T_SimpleCommand _ _ (cmd:_) ->+ let str = getLiteralStringDef "x" cmd+ last = lastOrDefault 'x' str+ in+ case str of+ "." -> return () -- The . command+ ":" -> return () -- The : command+ " " -> return () -- Probably caught by SC1101+ "//" -> return () -- Probably caught by SC1127+ "" -> err (getId cmd) 2286 "This empty string is interpreted as a command name. Double check syntax (or use 'true' as a no-op)."+ _ | last == '/' -> err (getId cmd) 2287 "This is interpreted as a command name ending with '/'. Double check syntax."+ _ | last `elem` "\\.,([{<>}])#\"\'% " -> warn (getId cmd) 2288 ("This is interpreted as a command name ending with " ++ (format last) ++ ". Double check syntax.")+ _ | '\t' `elem` str -> err (getId cmd) 2289 "This is interpreted as a command name containing a tab. Double check syntax."+ _ | '\n' `elem` str -> err (getId cmd) 2289 "This is interpreted as a command name containing a linefeed. Double check syntax."+ _ -> return ()+ _ -> return ()+ where+ format x =+ case x of+ ' ' -> "space"+ '\'' -> "apostrophe"+ '\"' -> "doublequote"+ x -> '\'' : x : "\'"+++prop_checkRequireDoubleBracket1 = verifyTree checkRequireDoubleBracket "[ -x foo ]"+prop_checkRequireDoubleBracket2 = verifyTree checkRequireDoubleBracket "[ foo -o bar ]"+prop_checkRequireDoubleBracket3 = verifyNotTree checkRequireDoubleBracket "#!/bin/sh\n[ -x foo ]"+prop_checkRequireDoubleBracket4 = verifyNotTree checkRequireDoubleBracket "[[ -x foo ]]"+prop_checkRequireDoubleBracket5 = verifyTreeFix checkRequireDoubleBracket "[ -x foo ]" "[[ -x foo ]]"+prop_checkRequireDoubleBracket6 = verifyTreeFix checkRequireDoubleBracket "[ -x foo ]]" "[[ -x foo ]]"+checkRequireDoubleBracket params =+ if (shellType params) `elem` [Bash, Ksh, BusyboxSh]+ then nodeChecksToTreeCheck [check] params+ else const []+ where+ check _ t = case t of+ T_Condition id SingleBracket _ _ ->+ styleWithFix id 2292 "Prefer [[ ]] over [ ] for tests in Bash/Ksh/Busybox." (fixFor t)+ _ -> return ()++ fixFor t = fixWith $+ if isSimple t+ then+ replaceStart (getId t) params 0 "[" :+ -- Don't add another ] if it was (wrongly) closed with ]] already+ [ replaceEnd (getId t) params 0 "]" | not $ isClosedWithDouble t ]+ else []++ isClosedWithDouble t = case t of+ T_Condition _ _ DoubleBracket _ -> True+ _ -> False++ -- We don't tag operators like < and -o well enough to replace them,+ -- so just handle the simple cases.+ isSimple t = case t of+ T_Condition _ _ _ s -> isSimple s+ TC_Binary _ _ op _ _ -> not $ any (\x -> x `elem` op) "<>"+ TC_Unary {} -> True+ TC_Nullary {} -> True+ _ -> False+++prop_checkRequireDoubleEquals1 = verifyTree checkRequireDoubleEquals "[[ \"$x\" = \"$y\" ]]"+prop_checkRequireDoubleEquals2 = verifyTree checkRequireDoubleEquals "[ \"$x\" = \"$y\" ]"+prop_checkRequireDoubleEquals3 = verifyNotTree checkRequireDoubleEquals "[[ \"$x\" == \"$y\" ]]"+prop_checkRequireDoubleEquals4 = verifyNotTree checkRequireDoubleEquals "#!/bin/sh\n[ \"$x\" = \"$y\" ]"+prop_checkRequireDoubleEquals5 = verifyNotTree checkRequireDoubleEquals "#!/bin/ksh\n[[ \"$x\" = \"$y\" ]]"+checkRequireDoubleEquals params =+ if shellType params == Bash+ then nodeChecksToTreeCheck [check] params+ else const []+ where+ check _ t = case t of+ TC_Binary id _ "=" _ _ ->+ style id 2338 "Prefer == over = for string comparisons in Bash tests."+ _ -> return ()+++prop_checkUnquotedParameterExpansionPattern1 = verify checkUnquotedParameterExpansionPattern "echo \"${var#$x}\""+prop_checkUnquotedParameterExpansionPattern2 = verify checkUnquotedParameterExpansionPattern "echo \"${var%%$(x)}\""+prop_checkUnquotedParameterExpansionPattern3 = verifyNot checkUnquotedParameterExpansionPattern "echo \"${var[#$x]}\""+prop_checkUnquotedParameterExpansionPattern4 = verifyNot checkUnquotedParameterExpansionPattern "echo \"${var%\"$x\"}\""++checkUnquotedParameterExpansionPattern params x =+ case x of+ T_DollarBraced _ True word@(T_NormalWord _ (T_Literal _ s : rest@(_:_))) -> do+ let modifier = getBracedModifier $ concat $ oversimplify word+ when ("%" `isPrefixOf` modifier || "#" `isPrefixOf` modifier) $+ mapM_ check rest+ _ -> return ()+ where+ check t =+ case t of+ T_DollarBraced {} -> inform t+ T_DollarExpansion {} -> inform t+ T_Backticked {} -> inform t+ _ -> return ()++ inform t =+ infoWithFix (getId t) 2295+ "Expansions inside ${..} need to be quoted separately, otherwise they match as patterns." $+ surroundWith (getId t) params "\""+++prop_checkArrayValueUsedAsIndex1 = verifyTree checkArrayValueUsedAsIndex "for i in ${arr[@]}; do echo ${arr[i]}; done"+prop_checkArrayValueUsedAsIndex2 = verifyTree checkArrayValueUsedAsIndex "for i in ${arr[@]}; do echo ${arr[$i]}; done"+prop_checkArrayValueUsedAsIndex3 = verifyTree checkArrayValueUsedAsIndex "for i in ${arr[@]}; do echo $((arr[i])); done"+prop_checkArrayValueUsedAsIndex4 = verifyTree checkArrayValueUsedAsIndex "for i in ${arr1[@]} ${arr2[@]}; do echo ${arr1[$i]}; done"+prop_checkArrayValueUsedAsIndex5 = verifyTree checkArrayValueUsedAsIndex "for i in ${arr1[@]} ${arr2[@]}; do echo ${arr2[$i]}; done"+prop_checkArrayValueUsedAsIndex7 = verifyNotTree checkArrayValueUsedAsIndex "for i in ${arr[@]}; do echo ${arr[K]}; done"+prop_checkArrayValueUsedAsIndex8 = verifyNotTree checkArrayValueUsedAsIndex "for i in ${arr[@]}; do i=42; echo ${arr[i]}; done"+prop_checkArrayValueUsedAsIndex9 = verifyNotTree checkArrayValueUsedAsIndex "for i in ${arr[@]}; do echo ${arr2[i]}; done"++checkArrayValueUsedAsIndex params _ =+ doVariableFlowAnalysis read write Map.empty (variableFlow params)+ where+ write loop@T_ForIn {} _ name (DataString (SourceFrom words)) = do+ modify $ Map.insert name (loop, mapMaybe f words)+ return []+ where+ f x = do+ name <- getArrayName x+ return (x, name)++ write _ _ name _ = do+ modify $ Map.delete name+ return []++ read _ t name = do+ varMap <- get+ return $ fromMaybe [] $ do+ (loop, arrays) <- Map.lookup name varMap+ (arrayRef, arrayName) <- getArrayIfUsedAsIndex name t+ -- Is this one of the 'for' arrays?+ (loopWord, _) <- find ((==arrayName) . snd) arrays+ -- Are we still in this loop?+ let loopId = getId loop+ guard $ any (\t -> loopId == getId t) (getPath parents t)+ return [+ makeComment WarningC (getId loopWord) 2302 "This loops over values. To loop over keys, use \"${!array[@]}\".",+ makeComment WarningC (getId arrayRef) 2303 $ (e4m name) ++ " is an array value, not a key. Use directly or loop over keys instead."+ ]++ parents = parentMap params++ getArrayName :: Token -> Maybe String+ getArrayName t = do+ [T_DollarBraced _ _ l] <- return $ getWordParts t+ let str = concat $ oversimplify l+ guard $ getBracedModifier str == "[@]" && not ("!" `isPrefixOf` str)+ return $ getBracedReference str++ -- This is much uglier than it should be+ getArrayIfUsedAsIndex :: String -> Token -> Maybe (Token, String)+ getArrayIfUsedAsIndex name t =+ case t of+ T_DollarBraced _ _ list -> do+ let ref = getBracedReference $ concat $ oversimplify list+ guard $ ref == name+ -- We found a $name. Look up the chain to see if it's ${arr[$name]}+ list@T_NormalWord {} <- Map.lookup (getId t) parents+ (T_DollarBraced _ _ parentList) <- Map.lookup (getId list) parents+ (T_Literal _ head : index : T_Literal _ tail : _) <- return $ getWordParts parentList+ let str = concat $ oversimplify list+ let modifier = getBracedModifier str+ guard $ getId index == getId t+ guard $ "[${VAR}]" `isPrefixOf` modifier+ return (t, getBracedReference str)++ T_NormalWord wordId list -> do+ -- We found just name. Check if it's part of ${something[name]}+ parent@(T_DollarBraced _ _ parentList) <- Map.lookup wordId parents+ let str = concat $ oversimplify t+ let modifier = getBracedModifier str+ guard $ ("[" ++ name ++ "]") `isPrefixOf` modifier+ return (parent, getBracedReference str)++ TA_Variable indexId ref [] -> do+ -- We found arithmetic name. See if it's part of arithmetic arr[name]+ guard $ ref == name+ (TA_Sequence seqId [element]) <- Map.lookup indexId parents+ guard $ getId element == indexId+ parent@(TA_Variable arrayId arrayName [element]) <- Map.lookup seqId parents+ guard $ getId element == seqId+ return (parent, arrayName)++ _ -> Nothing++prop_checkSetESuppressed1 = verifyTree checkSetESuppressed "set -e; f(){ :; }; x=$(f)"+prop_checkSetESuppressed2 = verifyNotTree checkSetESuppressed "f(){ :; }; x=$(f)"+prop_checkSetESuppressed3 = verifyNotTree checkSetESuppressed "set -e; f(){ :; }; x=$(set -e; f)"+prop_checkSetESuppressed4 = verifyTree checkSetESuppressed "set -e; f(){ :; }; baz=$(set -e; f) || :"+prop_checkSetESuppressed5 = verifyNotTree checkSetESuppressed "set -e; f(){ :; }; baz=$(echo \"\") || :"+prop_checkSetESuppressed6 = verifyTree checkSetESuppressed "set -e; f(){ :; }; f && echo"+prop_checkSetESuppressed7 = verifyTree checkSetESuppressed "set -e; f(){ :; }; f || echo"+prop_checkSetESuppressed8 = verifyNotTree checkSetESuppressed "set -e; f(){ :; }; echo && f"+prop_checkSetESuppressed9 = verifyNotTree checkSetESuppressed "set -e; f(){ :; }; echo || f"+prop_checkSetESuppressed10 = verifyTree checkSetESuppressed "set -e; f(){ :; }; ! f"+prop_checkSetESuppressed11 = verifyTree checkSetESuppressed "set -e; f(){ :; }; if f; then :; fi"+prop_checkSetESuppressed12 = verifyTree checkSetESuppressed "set -e; f(){ :; }; if set -e; f; then :; fi"+prop_checkSetESuppressed13 = verifyTree checkSetESuppressed "set -e; f(){ :; }; while f; do :; done"+prop_checkSetESuppressed14 = verifyTree checkSetESuppressed "set -e; f(){ :; }; while set -e; f; do :; done"+prop_checkSetESuppressed15 = verifyTree checkSetESuppressed "set -e; f(){ :; }; until f; do :; done"+prop_checkSetESuppressed16 = verifyTree checkSetESuppressed "set -e; f(){ :; }; until set -e; f; do :; done"+prop_checkSetESuppressed17 = verifyNotTree checkSetESuppressed "set -e; f(){ :; }; g(){ :; }; g f"+prop_checkSetESuppressed18 = verifyNotTree checkSetESuppressed "set -e; shopt -s inherit_errexit; f(){ :; }; x=$(f)"+prop_checkSetESuppressed19 = verifyNotTree checkSetESuppressed "set -e; set -o posix; f(){ :; }; x=$(f)"+prop_checkSetESuppressed20 = verifyTree checkSetESuppressed "set -e; set -o pipefail; f(){ :; }; x=$(f)"+prop_checkSetESuppressed21 = verifyTree checkSetESuppressed "set -e; set +o inherit_errexit; f(){ :; }; x=$(f)"+prop_checkSetESuppressed22 = verifyTree checkSetESuppressed "set -e; set -o vi; f(){ :; }; x=$(f)"+prop_checkSetESuppressed23 = verifyTree checkSetESuppressed "set -e; set -o noglob; f(){ :; }; x=$(f)"+prop_checkSetESuppressed24 = verifyNotTree checkSetESuppressed "set -e; shopt -s inherit_errexit; set -o pipefail; f(){ :; }; x=$(f)"+prop_checkSetESuppressed24B = verifyNotTree checkSetESuppressed "builtin set -e; builtin shopt -s inherit_errexit; builtin set -o pipefail; f(){ :; }; x=$(f)"+prop_checkSetESuppressed25 = verifyTree checkSetESuppressed "set -e; shopt -u inherit_errexit; set -o pipefail; f(){ :; }; x=$(f)"+prop_checkSetESuppressed26 = verifyTree checkSetESuppressed "set -e; set -euo pipefail; f(){ :; }; x=$(f)"+prop_checkSetESuppressed27 = verifyTree checkSetESuppressed "builtin set -e; builtin set -euo pipefail; f(){ :; }; x=$(f)"++checkSetESuppressed params t =+ if hasErrexit params then runNodeAnalysis checkNode params t else []+ where+ checkNode _ (T_SimpleCommand _ _ (cmd:_)) = when (isFunction cmd) (checkCmd cmd)+ checkNode _ _ = return ()++ functions_ = functions t++ isFunction cmd = isJust $ do+ literalArg <- getUnquotedLiteral cmd+ Map.lookup literalArg functions_++ checkCmd cmd = go $ NE.toList $ getPath (parentMap params) cmd+ where+ go (child:parent:rest) = do+ case parent of+ T_Banged _ condition | child `isIn` [condition] -> informConditional "a ! condition" cmd+ T_AndIf _ condition _ | child `isIn` [condition] -> informConditional "an && condition" cmd+ T_OrIf _ condition _ | child `isIn` [condition] -> informConditional "an || condition" cmd+ T_IfExpression _ condition _ | child `isIn` concatMap fst condition -> informConditional "an 'if' condition" cmd+ T_UntilExpression _ condition _ | child `isIn` condition -> informConditional "an 'until' condition" cmd+ T_WhileExpression _ condition _ | child `isIn` condition -> informConditional "a 'while' condition" cmd+ T_DollarExpansion {} | not $ errExitEnabled parent -> informUninherited cmd+ T_Backticked {} | not $ errExitEnabled parent -> informUninherited cmd+ _ -> return ()+ go (parent:rest)+ go _ = return ()++ informConditional condType t =+ info (getId t) 2310 (+ "This function is invoked in " ++ condType ++ " so set -e " +++ "will be disabled. Invoke separately if failures should " +++ "cause the script to exit.")+ informUninherited t =+ info (getId t) 2311 (+ "Bash implicitly disabled set -e for this function " +++ "invocation because it's inside a command substitution. " +++ "Add set -e; before it or enable inherit_errexit.")+ errExitEnabled t = hasInheritErrexit params || containsErrexit t+ isIn t cmds = getId t `elem` map getId cmds+++prop_checkExtraMaskedReturns1 = verifyTree checkExtraMaskedReturns "cat < <(ls)"+prop_checkExtraMaskedReturns2 = verifyTree checkExtraMaskedReturns "read -ra arr <(ls)"+prop_checkExtraMaskedReturns3 = verifyTree checkExtraMaskedReturns "ls >(cat)"+prop_checkExtraMaskedReturns4 = verifyTree checkExtraMaskedReturns "false | true"+prop_checkExtraMaskedReturns5 = verifyNotTree checkExtraMaskedReturns "set -o pipefail; false | true"+prop_checkExtraMaskedReturns6 = verifyNotTree checkExtraMaskedReturns "false | true || true"+prop_checkExtraMaskedReturns7 = verifyTree checkExtraMaskedReturns "true $(false)"+prop_checkExtraMaskedReturns8 = verifyTree checkExtraMaskedReturns "x=$(false)$(true)"+prop_checkExtraMaskedReturns9 = verifyNotTree checkExtraMaskedReturns "x=$(false)true"+prop_checkExtraMaskedReturns10 = verifyTree checkExtraMaskedReturns "x=`false``false`"+prop_checkExtraMaskedReturns11 = verifyTree checkExtraMaskedReturns "x=\"$(false)$(true)\""+prop_checkExtraMaskedReturns12 = verifyTree checkExtraMaskedReturns "x=\"$(false)\"\"$(true)\""+prop_checkExtraMaskedReturns13 = verifyTree checkExtraMaskedReturns "true <<<$(false)"+prop_checkExtraMaskedReturns14 = verifyNotTree checkExtraMaskedReturns "echo asdf | false"+prop_checkExtraMaskedReturns15 = verifyNotTree checkExtraMaskedReturns "readonly x=$(false)"+prop_checkExtraMaskedReturns16 = verifyTree checkExtraMaskedReturns "readarray -t files < <(ls)"+prop_checkExtraMaskedReturns17 = verifyNotTree checkExtraMaskedReturns "x=( $(false) false )"+prop_checkExtraMaskedReturns18 = verifyTree checkExtraMaskedReturns "x=( $(false) $(false) )"+prop_checkExtraMaskedReturns19 = verifyNotTree checkExtraMaskedReturns "x=( $(false) [4]=false )"+prop_checkExtraMaskedReturns20 = verifyTree checkExtraMaskedReturns "x=( $(false) [4]=$(false) )"+prop_checkExtraMaskedReturns21 = verifyTree checkExtraMaskedReturns "cat << foo\n $(false)\nfoo"+prop_checkExtraMaskedReturns22 = verifyTree checkExtraMaskedReturns "[[ $(false) ]]"+prop_checkExtraMaskedReturns23 = verifyNotTree checkExtraMaskedReturns "x=$(false) y=z"+prop_checkExtraMaskedReturns24 = verifyNotTree checkExtraMaskedReturns "x=$(( $(date +%s) ))"+prop_checkExtraMaskedReturns25 = verifyTree checkExtraMaskedReturns "echo $(( $(date +%s) ))"+prop_checkExtraMaskedReturns26 = verifyNotTree checkExtraMaskedReturns "x=( $(false) )"+prop_checkExtraMaskedReturns27 = verifyTree checkExtraMaskedReturns "x=$(false) false"+prop_checkExtraMaskedReturns28 = verifyTree checkExtraMaskedReturns "x=$(false) y=$(false)"+prop_checkExtraMaskedReturns29 = verifyNotTree checkExtraMaskedReturns "false < <(set -e)"+prop_checkExtraMaskedReturns30 = verifyNotTree checkExtraMaskedReturns "false < <(shopt -s cdspell)"+prop_checkExtraMaskedReturns31 = verifyNotTree checkExtraMaskedReturns "false < <(dirname \"${BASH_SOURCE[0]}\")"+prop_checkExtraMaskedReturns32 = verifyNotTree checkExtraMaskedReturns "false < <(basename \"${BASH_SOURCE[0]}\")"+prop_checkExtraMaskedReturns33 = verifyNotTree checkExtraMaskedReturns "{ false || true; } | true"+prop_checkExtraMaskedReturns34 = verifyNotTree checkExtraMaskedReturns "{ false || :; } | true"+prop_checkExtraMaskedReturns35 = verifyTree checkExtraMaskedReturns "f() { local -r x=$(false); }"+prop_checkExtraMaskedReturns36 = verifyNotTree checkExtraMaskedReturns "time false"+prop_checkExtraMaskedReturns37 = verifyNotTree checkExtraMaskedReturns "time $(time false)"+prop_checkExtraMaskedReturns38 = verifyTree checkExtraMaskedReturns "x=$(time time time false) time $(time false)"+prop_checkExtraMaskedReturns39 = verifyNotTree checkExtraMaskedReturns "eval \"$(false || echo exit 42)\""+prop_checkExtraMaskedReturns40 = verifyNotTree checkExtraMaskedReturns "eval \"$(git rev-parse --parseopt -- \"$@\" || echo exit $?)\""+prop_checkExtraMaskedReturns41 = verifyTree checkExtraMaskedReturns "true \"$(false || cat)\""++checkExtraMaskedReturns params t =+ runNodeAnalysis findMaskingNodes params (removeTransparentCommands t)+ where+ findMaskingNodes _ (T_Arithmetic _ list) = findMaskedNodesInList [list]+ findMaskingNodes _ (T_Array _ list) = findMaskedNodesInList $ allButLastSimpleCommands list+ findMaskingNodes _ (T_Condition _ _ _ condition) = findMaskedNodesInList [condition]+ findMaskingNodes _ (T_DoubleQuoted _ list) = findMaskedNodesInList $ allButLastSimpleCommands list+ findMaskingNodes _ (T_HereDoc _ _ _ _ list) = findMaskedNodesInList list+ findMaskingNodes _ (T_HereString _ word) = findMaskedNodesInList [word]+ findMaskingNodes _ (T_NormalWord _ parts) = findMaskedNodesInList $ allButLastSimpleCommands parts+ findMaskingNodes _ (T_Pipeline _ _ cmds) | not (hasPipefail params) = findMaskedNodesInList $ allButLastSimpleCommands cmds+ findMaskingNodes _ (T_ProcSub _ _ list) = findMaskedNodesInList list+ findMaskingNodes _ (T_SimpleCommand _ assigns (_:args)) = findMaskedNodesInList $ assigns ++ args+ findMaskingNodes _ (T_SimpleCommand _ assigns []) = findMaskedNodesInList $ allButLastSimpleCommands assigns+ findMaskingNodes _ _ = return ()++ findMaskedNodesInList = mapM_ (doAnalysis findMaskedNodes)++ isMaskedNode t = not (isHarmlessCommand t || isCheckedElsewhere t || isMaskDeliberate t)+ findMaskedNodes t@(T_SimpleCommand _ _ (_:_)) = when (isMaskedNode t) $ inform t+ findMaskedNodes t@T_Condition {} = when (isMaskedNode t) $ inform t+ findMaskedNodes _ = return ()++ containsSimpleCommand t = isNothing $ doAnalysis go t+ where+ go t = case t of+ T_SimpleCommand {} -> fail ""+ _ -> return ()++ allButLastSimpleCommands cmds =+ if null simpleCommands then [] else init simpleCommands+ where+ simpleCommands = filter containsSimpleCommand cmds++ removeTransparentCommands t =+ doTransform go t+ where+ go cmd@(T_SimpleCommand id assigns (_:args)) | isTransparentCommand cmd+ = T_SimpleCommand id assigns args+ go t = t++ inform t = info (getId t) 2312 ("Consider invoking this command "+ ++ "separately to avoid masking its return value (or use '|| true' "+ ++ "to ignore).")++ isMaskDeliberate t = any isOrIf $ NE.init $ parents params t+ where+ isOrIf (T_OrIf _ _ (T_Pipeline _ _ [T_Redirecting _ _ cmd]))+ = getCommandBasename cmd `elem` [Just "true", Just ":", Just "echo"]+ isOrIf _ = False++ isCheckedElsewhere t = any isDeclaringCommand $ NE.tail $ parents params t+ where+ isDeclaringCommand t = fromMaybe False $ do+ cmd <- getCommand t+ basename <- getCommandBasename cmd+ return $+ case basename of+ -- local -r x=$(false) is intentionally ignored for SC2155+ "local" | "r" `elem` (map snd $ getAllFlags cmd) -> False+ _ -> basename `elem` declaringCommands++ isHarmlessCommand t = fromMaybe False $ do+ basename <- getCommandBasename t+ return $ basename `elem` [+ "echo"+ ,"basename"+ ,"dirname"+ ,"printf"+ ,"set"+ ,"shopt"+ ]++ isTransparentCommand t = getCommandBasename t == Just "time"+++-- hard error on negated command that is not last+prop_checkBatsTestDoesNotUseNegation1 = verify checkBatsTestDoesNotUseNegation "#!/usr/bin/env/bats\n@test \"name\" { ! true; false; }"+prop_checkBatsTestDoesNotUseNegation2 = verify checkBatsTestDoesNotUseNegation "#!/usr/bin/env/bats\n@test \"name\" { ! [[ -e test ]]; false; }"+prop_checkBatsTestDoesNotUseNegation3 = verify checkBatsTestDoesNotUseNegation "#!/usr/bin/env/bats\n@test \"name\" { ! [ -e test ]; false; }"+-- acceptable formats:+-- using run+prop_checkBatsTestDoesNotUseNegation4 = verifyNot checkBatsTestDoesNotUseNegation "#!/usr/bin/env/bats\n@test \"name\" { run ! true; }"+-- using || false+prop_checkBatsTestDoesNotUseNegation5 = verifyNot checkBatsTestDoesNotUseNegation "#!/usr/bin/env/bats\n@test \"name\" { ! [[ -e test ]] || false; }"+prop_checkBatsTestDoesNotUseNegation6 = verifyNot checkBatsTestDoesNotUseNegation "#!/usr/bin/env/bats\n@test \"name\" { ! [ -e test ] || false; }"+-- only style warning when last command+prop_checkBatsTestDoesNotUseNegation7 = verifyCodes checkBatsTestDoesNotUseNegation [2314] "#!/usr/bin/env/bats\n@test \"name\" { ! true; }"+prop_checkBatsTestDoesNotUseNegation8 = verifyCodes checkBatsTestDoesNotUseNegation [2315] "#!/usr/bin/env/bats\n@test \"name\" { ! [[ -e test ]]; }"+prop_checkBatsTestDoesNotUseNegation9 = verifyCodes checkBatsTestDoesNotUseNegation [2315] "#!/usr/bin/env/bats\n@test \"name\" { ! [ -e test ]; }"++checkBatsTestDoesNotUseNegation params t =+ case t of+ T_BatsTest _ _ (T_BraceGroup _ commands) -> mapM_ (check commands) commands+ _ -> return ()+ where+ check commands t =+ case t of+ T_Banged id (T_Pipeline _ _ [T_Redirecting _ _ (T_Condition idCondition _ _ _)]) ->+ if t `isLastOf` commands+ then style id 2315 "In Bats, ! will not fail the test if it is not the last command anymore. Fold the `!` into the conditional!"+ else err id 2315 "In Bats, ! does not cause a test failure. Fold the `!` into the conditional!"++ T_Banged id cmd -> if t `isLastOf` commands+ then styleWithFix id 2314 "In Bats, ! will not fail the test if it is not the last command anymore. Use `run ! ` (on Bats >= 1.5.0) instead."+ (fixWith [replaceStart id params 0 "run "])+ else errWithFix id 2314 "In Bats, ! does not cause a test failure. Use 'run ! ' (on Bats >= 1.5.0) instead."+ (fixWith [replaceStart id params 0 "run "])+ _ -> return ()+ isLastOf t commands =+ case commands of+ [x] -> x == t+ x:rest -> isLastOf t rest+ [] -> False+++prop_checkCommandIsUnreachable1 = verify checkCommandIsUnreachable "foo; bar; exit; baz"+prop_checkCommandIsUnreachable2 = verify checkCommandIsUnreachable "die() { exit; }; foo; bar; die; baz"+prop_checkCommandIsUnreachable3 = verifyNot checkCommandIsUnreachable "foo; bar || exit; baz"+prop_checkCommandIsUnreachable4 = verifyNot checkCommandIsUnreachable "f() { foo; }; # Maybe sourced"+prop_checkCommandIsUnreachable5 = verify checkCommandIsUnreachable "f() { foo; }; exit # Not sourced"+prop_checkCommandIsUnreachable6 = verifyNot checkCommandIsUnreachable "f() { case x in *) : ;;& foo) return;; esac; echo x; }; f"+prop_checkCommandIsUnreachable7 = verify checkCommandIsUnreachable "f() { case x in *) return;; foo) return;; esac; echo x; }; f"+prop_checkCommandIsUnreachable8 = verify checkCommandIsUnreachable "f() { case x in foo) : ;;& *) return;; esac; echo x; }; f"+prop_checkCommandIsUnreachable9 = verifyNot checkCommandIsUnreachable "f() { case x in *) : ;;& foo) return;; bar) return;; esac; echo x; }; f"+prop_checkCommandIsUnreachable10 = verifyNot checkCommandIsUnreachable "f() { case x in *) : ;& foo) : ;;& bar) return;; esac; echo x; }; f"+prop_checkCommandIsUnreachable11 = verify checkCommandIsUnreachable "f() { case x in *) : ;& foo) return;; esac; echo x; }; f"+prop_checkCommandIsUnreachable12 = verifyNot checkCommandIsUnreachable "f() { case x in *) : ;;& foo) return;; *) :;; esac; echo x; }; f"+checkCommandIsUnreachable params t =+ case t of+ T_Pipeline {} -> sequence_ $ do+ cfga <- cfgAnalysis params+ state <- CF.getIncomingState cfga (getId t)+ guard . not $ CF.stateIsReachable state+ guard . not $ isSourced params t+ guard . not $ any (\t -> isUnreachable t || isUnreachableFunction t) $ NE.drop 1 $ getPath (parentMap params) t+ return $ info (getId t) 2317 "Command appears to be unreachable. Check usage (or ignore if invoked indirectly)."+ T_Function id _ _ _ _ ->+ when (isUnreachableFunction t+ && (not . any isUnreachableFunction . NE.drop 1 $ getPath (parentMap params) t)+ && (not $ isSourced params t)) $+ info id 2329 "This function is never invoked. Check usage (or ignored if invoked indirectly)."+ _ -> return ()+ where+ isUnreachableFunction :: Token -> Bool+ isUnreachableFunction f =+ case f of+ T_Function id _ _ _ t -> isUnreachable t+ _ -> False+ isUnreachable t = fromMaybe False $ do+ cfga <- cfgAnalysis params+ state <- CF.getIncomingState cfga (getId t)+ return . not $ CF.stateIsReachable state+++prop_checkOverwrittenExitCode1 = verify checkOverwrittenExitCode "x; [ $? -eq 1 ] || [ $? -eq 2 ]"+prop_checkOverwrittenExitCode2 = verifyNot checkOverwrittenExitCode "x; [ $? -eq 1 ]"+prop_checkOverwrittenExitCode3 = verify checkOverwrittenExitCode "x; echo \"Exit is $?\"; [ $? -eq 0 ]"+prop_checkOverwrittenExitCode4 = verifyNot checkOverwrittenExitCode "x; [ $? -eq 0 ] && echo Success"+prop_checkOverwrittenExitCode5 = verify checkOverwrittenExitCode "x; if [ $? -eq 0 ]; then var=$?; fi"+prop_checkOverwrittenExitCode5a = verify checkOverwrittenExitCode "x; if [ $? -eq 0 ]; then exit $?; fi"+prop_checkOverwrittenExitCode6 = verify checkOverwrittenExitCode "x; [ $? -gt 0 ] && fail=$?"+prop_checkOverwrittenExitCode6a = verify checkOverwrittenExitCode "x; [ $? -eq 0 ] && exit $?"+prop_checkOverwrittenExitCode7 = verifyNot checkOverwrittenExitCode "[ 1 -eq 2 ]; status=$?"+prop_checkOverwrittenExitCode8 = verifyNot checkOverwrittenExitCode "[ 1 -eq 2 ]; exit $?"+prop_checkOverwrittenExitCode9 = verifyNot checkOverwrittenExitCode "[[ -e \"./lockfile\" ]] || retval=$?"+prop_checkOverwrittenExitCode10 = verifyNot checkOverwrittenExitCode "[ -e \"./lockfile\" ] || retval=$?"+prop_checkOverwrittenExitCode11 = verifyNot checkOverwrittenExitCode "[ 1 -eq 2 ] && status=$?"+prop_checkOverwrittenExitCode12 = verify checkOverwrittenExitCode "x; printf '%d' $?; [ $? -eq 0 ]"+prop_checkOverwrittenExitCode13 = verifyNot checkOverwrittenExitCode "read -r x; [ $? -eq 0 ]"+prop_checkOverwrittenExitCode14 = verifyNot checkOverwrittenExitCode "x; echo $! > pid; [ $? -eq 0 ]"+prop_checkOverwrittenExitCode15 = verifyNot checkOverwrittenExitCode "x; printf \"%s\" \"$passwd\" >> /etc/passwd; [ $? -gt 0 ]"+prop_checkOverwrittenExitCode16 = verifyNot checkOverwrittenExitCode "x & echo $! > /var/something/pid; [ $? -eq 0 ] || ..."+checkOverwrittenExitCode params t =+ case t of+ T_DollarBraced id _ val | getLiteralString val == Just "?" -> check id+ _ -> return ()+ where+ check id = sequence_ $ do+ cfga <- cfgAnalysis params+ state <- CF.getIncomingState cfga id+ let exitCodeIds = CF.exitCodes state+ guard . not $ S.null exitCodeIds++ let idToToken = idMap params+ exitCodeTokens <- traverse (\k -> Map.lookup k idToToken) $ S.toList exitCodeIds+ let inAssignment = isInAssignment id+ condHasDollarQ = conditionContainsDollarQuestion id exitCodeIds+ suppress = inAssignment && not condHasDollarQ+ return $ do+ when (all isCondition exitCodeTokens+ && not (usedUnconditionally cfga t exitCodeIds)+ && not suppress) $+ warn id 2319 "This $? refers to a condition, not a command. Assign to a variable to avoid it being overwritten."+ when (all isPrinting exitCodeTokens+ && not suppress) $+ warn id 2320 "This $? refers to echo/printf, not a previous command. Assign to variable to avoid it being overwritten."++ isCondition t =+ case t of+ T_Condition {} -> True+ T_SimpleCommand {} -> getCommandName t == Just "test"+ _ -> False++ -- If we don't do anything based on the condition, assume we wanted the condition itself+ -- This helps differentiate `x; [ $? -gt 0 ] && exit $?` vs `[ cond ]; exit $?`+ usedUnconditionally cfga t testIds =+ all (\c -> CF.doesPostDominate cfga (getId t) c) testIds++ isPrinting t =+ if hasRedirection t == Just True+ then+ -- If the command writes somewhere, that's probably what the user wanted to check+ False+ else+ case getCommandBasename t of+ Just "echo" -> True+ Just "printf" -> True+ _ -> False++ hasRedirection :: Token -> Maybe Bool+ hasRedirection simpleCmd = do+ -- The CFG annotates exit statuses with their SimpleCommand, so we have to look up the surrounding Redircting:+ T_Redirecting _ list _ <- getClosestCommand (parentMap params) simpleCmd+ return . not . null $ list++ isInAssignment tokenId =+ let token = Map.lookup tokenId (idMap params)+ in maybe False (\tok -> any isAssignmentToken $ getPath (parentMap params) tok) token+ where+ isAssignmentToken (T_Assignment _ _ _ _ _) = True+ isAssignmentToken _ = False++ conditionContainsDollarQuestion tokenId exitIds =+ let tree = parentMap params+ tokenMap = idMap params+ condTokens = mapMaybe (`Map.lookup` tokenMap) (S.toList exitIds)+ dollarQTokens = [(tid, tok) | (tid, tok) <- Map.toList tokenMap,+ tid /= tokenId,+ isDollarQ tok]+ isDollarQ (T_DollarBraced _ _ val) = getLiteralString val == Just "?"+ isDollarQ _ = False+ in any (\(_, dqToken) ->+ any (\cond -> isParentOf tree cond dqToken) condTokens+ ) dollarQTokens+++prop_checkUnnecessaryArithmeticExpansionIndex1 = verify checkUnnecessaryArithmeticExpansionIndex "a[$((1+1))]=n"+prop_checkUnnecessaryArithmeticExpansionIndex2 = verifyNot checkUnnecessaryArithmeticExpansionIndex "a[1+1]=n"+prop_checkUnnecessaryArithmeticExpansionIndex3 = verifyNot checkUnnecessaryArithmeticExpansionIndex "a[$(echo $((1+1)))]=n"+prop_checkUnnecessaryArithmeticExpansionIndex4 = verifyNot checkUnnecessaryArithmeticExpansionIndex "declare -A a; a[$((1+1))]=val"+checkUnnecessaryArithmeticExpansionIndex params t =+ case t of+ T_Assignment _ mode var [TA_Sequence _ [ TA_Expansion _ [expansion@(T_DollarArithmetic id _)]]] val ->+ styleWithFix id 2321 "Array indices are already arithmetic contexts. Prefer removing the $(( and ))." $ fix id+ _ -> return ()++ where+ fix id =+ fixWith [+ replaceStart id params 3 "", -- Remove "$(("+ replaceEnd id params 2 "" -- Remove "))"+ ]+++prop_checkUnnecessaryParens1 = verify checkUnnecessaryParens "echo $(( ((1+1)) ))"+prop_checkUnnecessaryParens2 = verify checkUnnecessaryParens "x[((1+1))+1]=1"+prop_checkUnnecessaryParens3 = verify checkUnnecessaryParens "x[(1+1)]=1"+prop_checkUnnecessaryParens4 = verify checkUnnecessaryParens "$(( (x) ))"+prop_checkUnnecessaryParens5 = verify checkUnnecessaryParens "(( (x) ))"+prop_checkUnnecessaryParens6 = verifyNot checkUnnecessaryParens "x[(1+1)+1]=1"+prop_checkUnnecessaryParens7 = verifyNot checkUnnecessaryParens "(( (1*1)+1 ))"+prop_checkUnnecessaryParens8 = verifyNot checkUnnecessaryParens "(( (1)+1 ))"+checkUnnecessaryParens params t =+ case t of+ T_DollarArithmetic _ t -> checkLeading "$(( (x) )) is the same as $(( x ))" t+ T_ForArithmetic _ x y z _ -> mapM_ (checkLeading "for (((x); (y); (z))) is the same as for ((x; y; z))") [x,y,z]+ T_Assignment _ _ _ [t] _ -> checkLeading "a[(x)] is the same as a[x]" t+ T_Arithmetic _ t -> checkLeading "(( (x) )) is the same as (( x ))" t+ TA_Parenthesis _ (TA_Sequence _ [ TA_Parenthesis id _ ]) ->+ styleWithFix id 2322 "In arithmetic contexts, ((x)) is the same as (x). Prefer only one layer of parentheses." $ fix id+ _ -> return ()+ where++ checkLeading str t =+ case t of+ TA_Sequence _ [TA_Parenthesis id _ ] -> styleWithFix id 2323 (str ++ ". Prefer not wrapping in additional parentheses.") $ fix id+ _ -> return ()++ fix id =+ fixWith [+ replaceStart id params 1 "", -- Remove "("+ replaceEnd id params 1 "" -- Remove ")"+ ]+++prop_checkPlusEqualsNumber1 = verify checkPlusEqualsNumber "x+=1"+prop_checkPlusEqualsNumber2 = verify checkPlusEqualsNumber "x+=42"+prop_checkPlusEqualsNumber3 = verifyNot checkPlusEqualsNumber "(( x += 1 ))"+prop_checkPlusEqualsNumber4 = verifyNot checkPlusEqualsNumber "declare -i x=0; x+=1"+prop_checkPlusEqualsNumber5 = verifyNot checkPlusEqualsNumber "x+='1'"+prop_checkPlusEqualsNumber6 = verifyNot checkPlusEqualsNumber "n=foo; x+=n"+prop_checkPlusEqualsNumber7 = verify checkPlusEqualsNumber "n=4; x+=n"+prop_checkPlusEqualsNumber8 = verify checkPlusEqualsNumber "n=4; x+=$n"+prop_checkPlusEqualsNumber9 = verifyNot checkPlusEqualsNumber "declare -ia var; var[x]+=1"+checkPlusEqualsNumber params t =+ case t of+ T_Assignment id Append var _ word -> sequence_ $ do+ cfga <- cfgAnalysis params+ state <- CF.getIncomingState cfga id+ guard $ isNumber state word+ guard . not $ fromMaybe False $ CF.variableMayBeDeclaredInteger state var+ -- Recommend "typeset" because ksh does not have "declare".+ return $ warn id 2324 "var+=1 will append, not increment. Use (( var += 1 )), typeset -i var, or quote number to silence."+ _ -> return ()++ where+ isNumber state word =+ let+ unquotedLiteral = getUnquotedLiteral word+ isEmpty = unquotedLiteral == Just ""+ isUnquotedNumber = not isEmpty && maybe False (all isDigit) unquotedLiteral+ isNumericalVariableName = fromMaybe False $ do+ str <- unquotedLiteral+ CF.variableMayBeAssignedInteger state str+ isNumericalVariableExpansion =+ case word of+ T_NormalWord _ [part] -> fromMaybe False $ do+ str <- getUnmodifiedParameterExpansion part+ CF.variableMayBeAssignedInteger state str+ _ -> False+ in+ isUnquotedNumber || isNumericalVariableName || isNumericalVariableExpansion++++prop_checkExpansionWithRedirection1 = verify checkExpansionWithRedirection "var=$(foo > bar)"+prop_checkExpansionWithRedirection2 = verify checkExpansionWithRedirection "var=`foo 1> bar`"+prop_checkExpansionWithRedirection3 = verify checkExpansionWithRedirection "var=${ foo >> bar; }"+prop_checkExpansionWithRedirection4 = verify checkExpansionWithRedirection "var=$(foo | bar > baz)"+prop_checkExpansionWithRedirection5 = verifyNot checkExpansionWithRedirection "stderr=$(foo 2>&1 > /dev/null)"+prop_checkExpansionWithRedirection6 = verifyNot checkExpansionWithRedirection "var=$(foo; bar > baz)"+prop_checkExpansionWithRedirection7 = verifyNot checkExpansionWithRedirection "var=$(foo > bar; baz)"+prop_checkExpansionWithRedirection8 = verifyNot checkExpansionWithRedirection "var=$(cat <&3)"+checkExpansionWithRedirection params t =+ case t of+ T_DollarExpansion id [cmd] -> check id cmd+ T_Backticked id [cmd] -> check id cmd+ T_DollarBraceCommandExpansion id _ [cmd] -> check id cmd+ _ -> return ()+ where+ check id pipe =+ case pipe of+ (T_Pipeline _ _ t@(_:_)) -> checkCmd id (last t)+ _ -> return ()++ checkCmd captureId (T_Redirecting _ redirs _) = foldr (walk captureId) (return ()) redirs+ checkCmd _ _ = return ()++ walk captureId t acc =+ case t of+ T_FdRedirect _ _ (T_IoDuplicate _ _ "1") -> return ()+ T_FdRedirect id "1" (T_IoDuplicate _ _ _) -> return ()+ T_FdRedirect id "" (T_IoDuplicate _ op _) | op `elem` [T_GREATAND (Id 0), T_Greater (Id 0)] -> emit id captureId True+ T_FdRedirect id str (T_IoFile _ op file) | str `elem` ["", "1"] && op `elem` [ T_DGREAT (Id 0), T_Greater (Id 0) ] ->+ emit id captureId $ getLiteralString file /= Just "/dev/null"+ _ -> acc++ emit redirectId captureId suggestTee = do+ warn captureId 2327 "This command substitution will be empty because the command's output gets redirected away."+ err redirectId 2328 $ "This redirection takes output away from the command substitution" ++ if suggestTee then " (use tee to duplicate)." else "."+++prop_checkUnaryTestA1 = verify checkUnaryTestA "[ -a foo ]"+prop_checkUnaryTestA2 = verify checkUnaryTestA "[ ! -a foo ]"+prop_checkUnaryTestA3 = verifyNot checkUnaryTestA "[ foo -a bar ]"+checkUnaryTestA params t =+ case t of+ TC_Unary id _ "-a" _ ->+ styleWithFix id 2331 "For file existence, prefer standard -e over legacy -a." $+ fixWith [replaceStart id params 2 "-e"]+ _ -> return () return [] runTests = $( [| $(forAllProperties) (quickCheckWithResult (stdArgs { maxSuccess = 1 }) ) |])
src/ShellCheck/AnalyzerLib.hs view
@@ -41,6 +41,7 @@ import Data.List import Data.Maybe import Data.Semigroup+import qualified Data.List.NonEmpty as NE import qualified Data.Map as Map import Test.QuickCheck.All (forAllProperties)@@ -80,14 +81,20 @@ composeAnalyzers f g x = f x >> g x data Parameters = Parameters {+ -- Whether this script has 'set -a' or 'set -o allexport' anywhere.+ hasAllexport :: Bool, -- Whether this script has the 'lastpipe' option set/default. hasLastpipe :: Bool, -- Whether this script has the 'inherit_errexit' option set/default. hasInheritErrexit :: Bool,- -- Whether this script has 'set -e' anywhere.- hasSetE :: Bool,+ -- Whether this script has 'set -e' or 'set -o errexit' anywhere.+ hasErrexit :: Bool,+ -- Whether this script has 'set -f' or 'set -o noglob' anywhere.+ hasNoglob :: Bool, -- Whether this script has 'set -o pipefail' anywhere. hasPipefail :: Bool,+ -- Whether this script has 'shopt -s execfail' anywhere.+ hasExecfail :: Bool, -- A linear (bad) analysis of data flow variableFlow :: [StackData], -- A map from Id to Token@@ -103,13 +110,13 @@ -- map from token id to start and end position tokenPositions :: Map.Map Id (Position, Position), -- Result from Control Flow Graph analysis (including data flow analysis)- cfgAnalysis :: CF.CFGAnalysis+ cfgAnalysis :: Maybe CF.CFGAnalysis } deriving (Show) -- TODO: Cache results of common AST ops here data Cache = Cache {} -data Scope = SubshellScope String | NoneScope deriving (Show, Eq)+data Scope = SubshellScope String | FunctionScope | NoneScope deriving (Show, Eq) data StackData = StackScope Scope | StackScopeEnd@@ -148,12 +155,16 @@ -- For testing. If parsed, returns whether there are any comments producesComments :: Checker -> String -> Maybe Bool-producesComments c s = do+producesComments c s = fmap (not . null) $ runAndGetCodes c s++-- If parsed, returns the list of codes+runAndGetCodes :: Checker -> String -> Maybe [Integer]+runAndGetCodes c s = do let pr = pScript s prRoot pr let spec = defaultSpec pr let params = makeParameters spec- return . not . null $ filterByAnnotation spec params $ runChecker params c+ return . (sort . map (cCode . tcComment)) $ filterByAnnotation spec params $ runChecker params c makeComment :: Severity -> Id -> Code -> String -> TokenComment makeComment severity id code note =@@ -196,82 +207,99 @@ } in force withFix +extendedAnalysisAnnotationToMode :: ExtendedAnalysisAnnotation -> ExtendedAnalysisMode+extendedAnalysisAnnotationToMode m =+ case m of+ EAANone -> ExtendedAnalysisNone+ EAALocal -> ExtendedAnalysisLocal+ EAAFull -> ExtendedAnalysisFull++-- makeParameters :: CheckSpec -> Parameters makeParameters spec = params where+ extendedAnalysisMode = fromMaybe ExtendedAnalysisFull $+ msum [asExtendedAnalysis spec, extendedAnalysisAnnotationToMode <$> getExtendedAnalysisDirective root] params = Parameters { rootNode = root, shellType = fromMaybe (determineShell (asFallbackShell spec) root) $ asShellType spec,- hasSetE = containsSetE root,+ hasAllexport = containsAllexport root,+ hasErrexit = containsErrexit root,+ hasNoglob = containsNoglob root, hasLastpipe = case shellType params of- Bash -> isOptionSet "lastpipe" root+ Bash -> containsLastpipe root Dash -> False+ BusyboxSh -> False Sh -> False Ksh -> True, hasInheritErrexit = case shellType params of- Bash -> isOptionSet "inherit_errexit" root+ -- POSIX mode enables inherit_errexit by default in Bash.+ Bash -> containsInheritErrexit root || containsPosix root Dash -> True+ BusyboxSh -> True Sh -> True Ksh -> False,- hasPipefail =+ hasPipefail = containsPipefail root,+ hasExecfail = case shellType params of- Bash -> isOptionSet "pipefail" root- Dash -> True- Sh -> True- Ksh -> isOptionSet "pipefail" root,+ Bash -> containsExecfail root+ _ -> False, shellTypeSpecified = isJust (asShellType spec) || isJust (asFallbackShell spec), idMap = getTokenMap root, parentMap = getParentTree root, variableFlow = getVariableFlow params root, tokenPositions = asTokenPositions spec,- cfgAnalysis = CF.analyzeControlFlow cfParams root+ cfgAnalysis = do+ guard $ extendedAnalysisMode /= ExtendedAnalysisNone+ return $ CF.analyzeControlFlow cfParams root } cfParams = CF.CFGParameters { CF.cfLastpipe = hasLastpipe params,- CF.cfPipefail = hasPipefail params+ CF.cfPipefail = hasPipefail params,+ -- In 'local' mode, sourced files are data-flow boundaries: their+ -- bodies are not inlined into the CFG (bounds memory on large+ -- mutually-sourcing trees). See CFG.cfSourceAsBoundary.+ CF.cfSourceAsBoundary = extendedAnalysisMode == ExtendedAnalysisLocal } root = asScript spec ---- Does this script mention 'set -e' anywhere?--- Used as a hack to disable certain warnings.-containsSetE root = isNothing $ doAnalysis (guard . not . isSetE) root+-- Detect shell option (`set -o errexit`, `shopt -o -s errexit`, `set -e`, `#!/bin/sh -e`)+-- This is a hack that does not account for flow control, but helps disable certain warnings+isOptionSet :: [Char] -> Maybe Char -> Token -> Bool+isOptionSet longOpt shortOpt root = isNothing $ doAnalysis (guard . not . isSetOption) root where- isSetE t =+ shebangRegex c = mkRegex $ "[[:space:]]-[^-]*" ++ [c]+ isSetOption t = case t of- T_Script _ (T_Literal _ str) _ -> str `matches` re- T_SimpleCommand {} ->- t `isUnqualifiedCommand` "set" &&- ("errexit" `elem` oversimplify t ||- "e" `elem` map snd (getAllFlags t))- _ -> False- re = mkRegex "[[:space:]]-[^-]*e"-+ T_Script _ (T_Literal _ str) _ | isJust shortOpt ->+ str `matches` shebangRegex (fromJust shortOpt) -containsSetOption opt root = isNothing $ doAnalysis (guard . not . isPipefail) root- where- isPipefail t =- case t of- T_SimpleCommand {} ->- t `isUnqualifiedCommand` "set" &&- (opt `elem` oversimplify t ||- "o" `elem` map snd (getAllFlags t))+ T_SimpleCommand {} -> fromMaybe False $ do+ cmd <- getCommandName t+ let flags = map snd $ getAllFlags t+ let strings = oversimplify t+ return $ case cmd of+ "set" ->+ (longOpt `elem` strings && "o" `elem` flags) ||+ isJust shortOpt && [fromJust shortOpt] `elem` flags+ "shopt" ->+ longOpt `elem` strings && "s" `elem` flags+ _ -> False _ -> False -containsShopt shopt root =- isNothing $ doAnalysis (guard . not . isShoptLastPipe) root- where- isShoptLastPipe t =- case t of- T_SimpleCommand {} ->- t `isUnqualifiedCommand` "shopt" &&- (shopt `elem` oversimplify t)- _ -> False+containsErrexit = isOptionSet "errexit" (Just 'e')+containsAllexport = isOptionSet "allexport" (Just 'a')+containsNoglob = isOptionSet "noglob" (Just 'f')+containsPipefail = isOptionSet "pipefail" Nothing+containsLastpipe = isOptionSet "lastpipe" Nothing+containsExecfail = isOptionSet "execfail" Nothing+containsInheritErrexit = isOptionSet "inherit_errexit" Nothing+containsPosix = isOptionSet "posix" Nothing --- Does this script mention 'shopt -s $opt' or 'set -o $opt' anywhere?-isOptionSet opt root = containsShopt opt root || containsSetOption opt root +-- Make sure all shells in supportedShellDialects resolve with shellForExecutable+prop_supportedShellsResolve = isJust $ sequence $ map shellForExecutable supportedShellDialects prop_determineShell0 = determineShellTest "#!/bin/sh" == Sh prop_determineShell1 = determineShellTest "#!/usr/bin/env ksh" == Ksh@@ -284,20 +312,18 @@ prop_determineShell8 = determineShellTest' (Just Ksh) "#!/bin/sh" == Sh prop_determineShell9 = determineShellTest "#!/bin/env -S dash -x" == Dash prop_determineShell10 = determineShellTest "#!/bin/env --split-string= dash -x" == Dash-prop_determineShell11 = determineShellTest "#!/bin/busybox sh" == Dash -- busybox sh is a specific shell, not posix sh-prop_determineShell12 = determineShellTest "#!/bin/busybox ash" == Dash+prop_determineShell11 = determineShellTest "#!/bin/busybox sh" == BusyboxSh -- busybox sh is a specific shell, not posix sh+prop_determineShell12 = determineShellTest "#!/bin/busybox ash" == BusyboxSh determineShellTest = determineShellTest' Nothing determineShellTest' fallbackShell = determineShell fallbackShell . fromJust . prRoot . pScript determineShell fallbackShell t = fromMaybe Bash $- shellForExecutable shellString `mplus` fallbackShell+ getCandidate t `mplus` fallbackShell where- shellString = getCandidate t- getCandidate :: Token -> String- getCandidate t@T_Script {} = fromShebang t- getCandidate (T_Annotation _ annotations s) =- headOrDefault (fromShebang s) [s | ShellOverride s <- annotations]- fromShebang (T_Script _ (T_Literal _ s) _) = executableFromShebang s+ getCandidate (T_Annotation _ annotations s) = fromScript annotations s+ getCandidate s = fromScript [] s+ fromScript annotations (T_Script _ (T_Literal _ s) _) =+ shellFromAnnotations annotations (executableFromShebang s) -- Given a root node, make a map from Id to parent Token. -- This is used to populate parentMap in Parameters@@ -333,14 +359,14 @@ isQuoteFreeNode strict shell tree t = isQuoteFreeElement t ||- (fromMaybe False $ msum $ map isQuoteFreeContext $ drop 1 $ getPath tree t)+ (fromMaybe False $ msum $ map isQuoteFreeContext $ NE.tail $ getPath tree t) where -- Is this node self-quoting in itself? isQuoteFreeElement t = case t of- T_Assignment {} -> assignmentIsQuoting t- T_FdRedirect {} -> True- _ -> False+ T_Assignment id _ _ _ _ -> assignmentIsQuoting id+ T_FdRedirect {} -> True+ _ -> False -- Are any subnodes inherently self-quoting? isQuoteFreeContext t =@@ -350,7 +376,7 @@ TC_Binary _ DoubleBracket _ _ _ -> return True TA_Sequence {} -> return True T_Arithmetic {} -> return True- T_Assignment {} -> return $ assignmentIsQuoting t+ T_Assignment id _ _ _ _ -> return $ assignmentIsQuoting id T_Redirecting {} -> return False T_DoubleQuoted _ _ -> return True T_DollarDoubleQuoted _ _ -> return True@@ -365,11 +391,11 @@ -- Check whether this assignment is self-quoting due to being a recognized -- assignment passed to a Declaration Utility. This will soon be required -- by POSIX: https://austingroupbugs.net/view.php?id=351- assignmentIsQuoting t = shellParsesParamsAsAssignments || not (isAssignmentParamToCommand t)+ assignmentIsQuoting id = shellParsesParamsAsAssignments || not (isAssignmentParamToCommand id) shellParsesParamsAsAssignments = shell /= Sh -- Is this assignment a parameter to a command like export/typeset/etc?- isAssignmentParamToCommand (T_Assignment id _ _ _ _) =+ isAssignmentParamToCommand id = case Map.lookup id tree of Just (T_SimpleCommand _ _ (_:args)) -> id `elem` (map getId args) _ -> False@@ -395,7 +421,7 @@ -- Get the parent command (T_Redirecting) of a Token, if any. getClosestCommand :: Map.Map Id Token -> Token -> Maybe Token getClosestCommand tree t =- findFirst findCommand $ getPath tree t+ findFirst findCommand $ NE.toList $ getPath tree t where findCommand t = case t of@@ -409,7 +435,7 @@ return $ getClosestCommand (parentMap params) t -- Is the token used as a command name (the first word in a T_SimpleCommand)?-usedAsCommandName tree token = go (getId token) (tail $ getPath tree token)+usedAsCommandName tree token = go (getId token) (NE.tail $ getPath tree token) where go currentId (T_NormalWord id [word]:rest) | currentId == getId word = go id rest@@ -426,7 +452,9 @@ return $ getPath (parentMap params) t isParentOf tree parent child =- elem (getId parent) . map getId $ getPath tree child+ any (\t -> parentId == getId t) (getPath tree child)+ where+ parentId = getId parent parents params = getPath (parentMap params) @@ -488,9 +516,11 @@ T_DollarExpansion _ _ -> SubshellScope "$(..) expansion" T_Backticked _ _ -> SubshellScope "`..` expansion" T_Backgrounded _ _ -> SubshellScope "backgrounding &"+ T_KshCoprocess _ _ -> SubshellScope "backgrounding |&" T_Subshell _ _ -> SubshellScope "(..) group" T_BatsTest {} -> SubshellScope "@bats test" T_CoProcBody _ _ -> SubshellScope "coproc"+ T_Function {} -> FunctionScope T_Redirecting {} -> if causesSubshell == Just True then SubshellScope "pipeline"@@ -525,7 +555,9 @@ T_BatsTest {} -> [ (t, t, "lines", DataArray SourceExternal), (t, t, "status", DataString SourceInteger),- (t, t, "output", DataString SourceExternal)+ (t, t, "output", DataString SourceExternal),+ (t, t, "stderr", DataString SourceExternal),+ (t, t, "stderr_lines", DataArray SourceExternal) ] -- Count [[ -v foo ]] as an "assignment".@@ -547,9 +579,13 @@ T_FdRedirect _ ('{':var) op -> -- {foo}>&2 modifies foo [(t, t, takeWhile (/= '}') var, DataString SourceInteger) | not $ isClosingFileOp op] - T_CoProc _ name _ ->- [(t, t, fromMaybe "COPROC" name, DataArray SourceInteger)]+ T_CoProc _ Nothing _ ->+ [(t, t, "COPROC", DataArray SourceInteger)] + T_CoProc _ (Just token) _ -> do+ name <- maybeToList $ getLiteralString token+ [(t, t, name, DataArray SourceInteger)]+ --Points to 'for' rather than variable T_ForIn id str [] _ -> [(t, t, str, DataString SourceExternal)] T_ForIn id str words _ -> [(t, t, str, DataString $ SourceFrom words)]@@ -565,6 +601,20 @@ _ -> Nothing +-- Variables set by bats' run command+getBatsRunVariables args =+ [+ ("status", DataString SourceInteger),+ ("output", DataString SourceExternal),+ ("lines", DataArray SourceExternal)+ ] ++ if "--separate-stderr" `elem` opts then [+ ("stderr", DataString SourceExternal),+ ("stderr_lines", DataArray SourceExternal)+ ] else []+ where+ opts = takeWhile (\s -> s == "!" || (s /= "--" && "-" `isPrefixOf` s)) $+ map (fromMaybe "" . getLiteralString) args+ -- Consider 'export/declare -x' a reference, since it makes the var available getReferencedVariableCommand base@(T_SimpleCommand _ _ (T_NormalWord _ (T_Literal _ x:_):rest)) = case x of@@ -647,12 +697,15 @@ "mapfile" -> maybeToList $ getMapfileArray base rest "readarray" -> maybeToList $ getMapfileArray base rest+ "compgen" -> maybeToList $ getCompgenArray rest "DEFINE_boolean" -> maybeToList $ getFlagVariable rest "DEFINE_float" -> maybeToList $ getFlagVariable rest "DEFINE_integer" -> maybeToList $ getFlagVariable rest "DEFINE_string" -> maybeToList $ getFlagVariable rest + "run" -> [(base, base, name, value) | (name, value) <- getBatsRunVariables rest]+ _ -> [] where flags = map snd $ getAllFlags base@@ -706,6 +759,14 @@ getPrintfVariable list = getFlagAssignedVariable "v" (SourceFrom list) $ getBsdOpts "v:" list getWaitVariable list = getFlagAssignedVariable "p" SourceInteger $ return $ getGenericOpts list + -- compgen -V arr stores the completions in the array arr rather than printing them+ getCompgenArray list = do+ let flags = getGenericOpts list+ (_, (_, value)) <- find ((== "V") . fst) flags+ name <- getLiteralString value+ guard $ isVariableName name+ return (base, value, name, DataArray SourceExternal)+ getFlagAssignedVariable str dataSource maybeFlags = do flags <- maybeFlags (_, (flag, value)) <- find ((== str) . fst) flags@@ -780,12 +841,6 @@ then concatMap (getIfReference t) [lhs, rhs] else [] - T_BatsTest {} -> [ -- pretend @test references vars to avoid warnings- (t, t, "lines"),- (t, t, "status"),- (t, t, "output")- ]- T_FdRedirect _ ('{':var) op -> -- {foo}>&- references and closes foo [(t, t, takeWhile (/= '}') var) | isClosingFileOp op] x -> getReferencedVariableCommand x@@ -810,7 +865,7 @@ return (context, token, getBracedReference str) isArithmeticAssignment t = case getPath parents t of- this: TA_Assignment _ "=" lhs _ :_ -> lhs == t+ this NE.:| TA_Assignment _ "=" lhs _ :_ -> lhs == t _ -> False isDereferencingBinaryOp = (`elem` ["-eq", "-ne", "-lt", "-le", "-gt", "-ge"])@@ -892,15 +947,6 @@ supportsArrays Ksh = True supportsArrays _ = False --- Returns true if the shell is Bash or Ksh (sorry for the name, Ksh)-isBashLike :: Parameters -> Bool-isBashLike params =- case shellType params of- Bash -> True- Ksh -> True- Dash -> False- Sh -> False- isTrueAssignmentSource c = case c of DataString SourceChecked -> False@@ -917,6 +963,30 @@ case t of Assignment (_, _, n, source) -> isTrueAssignmentSource source && n == name _ -> False++isTestCommand t =+ case t of+ T_Condition {} -> True+ T_SimpleCommand {} -> t `isCommand` "test"+ T_Redirecting _ _ t -> isTestCommand t+ T_Annotation _ _ t -> isTestCommand t+ T_Pipeline _ _ [t] -> isTestCommand t+ _ -> False++-- Checks whether the current parent path is part of a condition+isCondition (x NE.:| xs) = foldr go (const False) xs x+ where+ go _ _ T_BatsTest{} = True -- count anything in a @test as conditional+ go parent go_rest child =+ getId child `elem` map getId (getConditionChildren parent) || go_rest parent+ getConditionChildren t =+ case t of+ T_AndIf _ left right -> [left]+ T_OrIf id left right -> [left]+ T_IfExpression id conditions elses -> concatMap (take 1 . reverse . fst) conditions+ T_WhileExpression id c l -> take 1 . reverse $ c+ T_UntilExpression id c l -> take 1 . reverse $ c+ _ -> [] return []
src/ShellCheck/CFG.hs view
@@ -51,6 +51,7 @@ import Data.Array.Unboxed import Data.Array.ST import Data.List hiding (map)+import qualified Data.List.NonEmpty as NE import Data.Maybe import qualified Data.Map as M import qualified Data.Set as S@@ -111,8 +112,8 @@ -- Actions we track data CFEffect =- CFSetProps Scope String (S.Set CFVariableProp)- | CFUnsetProps Scope String (S.Set CFVariableProp)+ CFSetProps (Maybe Scope) String (S.Set CFVariableProp)+ | CFUnsetProps (Maybe Scope) String (S.Set CFVariableProp) | CFReadVariable String | CFWriteVariable String CFValue | CFWriteGlobal String CFValue@@ -159,7 +160,7 @@ deriving (Eq, Ord, Show, Generic, NFData) -- The properties of a variable-data CFVariableProp = CFVPExport | CFVPArray | CFVPAssociative | CFVPInteger+data CFVariableProp = CFVPExport | CFVPArray | CFVPAssociative | CFVPInteger | CFVPReadonly deriving (Eq, Ord, Show, Generic, NFData) -- Options when generating CFG@@ -167,7 +168,11 @@ -- Whether the last element in a pipeline runs in the current shell cfLastpipe :: Bool, -- Whether all elements in a pipeline count towards the exit status- cfPipefail :: Bool+ cfPipefail :: Bool,+ -- Treat 'source'd files as data-flow boundaries: don't inline their+ -- bodies into the CFG. Bounds memory when many inputs source a shared+ -- tree (each includer would otherwise re-analyze the whole tree).+ cfSourceAsBoundary :: Bool } data CFGResult = CFGResult {@@ -192,7 +197,7 @@ base idToRange = M.fromList mapping- isRealEdge (from, to, edge) = case edge of CFEFlow -> True; _ -> False+ isRealEdge (from, to, edge) = case edge of CFEFlow -> True; CFEExit -> True; _ -> False onlyRealEdges = filter isRealEdge edges (_, mainExit) = fromJust $ M.lookup (getId root) idToRange @@ -269,10 +274,10 @@ [(Id 0, 3)] ) after = (- [(1,s), (2,s), (4,s)],- [(1,2,CFEFlow), (2,4,CFEFlow)],- [(Id 0, (2,2))],- [(Id 0, 2)]+ [(1,s), (3,s), (4,s)],+ [(1,3,CFEFlow), (3,4,CFEFlow)],+ [(Id 0, (3,3))],+ [(Id 0, 3)] ) in after == removeUnnecessaryStructuralNodes before @@ -292,21 +297,20 @@ ) where regularEdges = filter isRegularEdge edges- inDegree = counter $ map (\(from,to,_) -> from) regularEdges- outDegree = counter $ map (\(from,to,_) -> to) regularEdges- structuralNodes = S.fromList $ map fst $ filter isStructural nodes+ inDegree = counter $ map (\(from,to,_) -> to) regularEdges+ outDegree = counter $ map (\(from,to,_) -> from) regularEdges+ structuralNodes = S.fromList [node | (node, CFStructuralNode) <- nodes] candidateNodes = S.filter isLinear structuralNodes edgesToCollapse = S.fromList $ filter filterEdges regularEdges remapping :: M.Map Node Node- remapping = foldl' (\m (new, old) -> M.insert old new m) M.empty $ map orderEdge $ S.toList edgesToCollapse- recursiveRemapping = M.fromList $ map (\c -> (c, recursiveLookup remapping c)) $ M.keys remapping+ remapping = M.fromList $ map (\(a,b,_) -> (a,b)) $ S.toList edgesToCollapse+ recursiveRemapping = M.mapWithKey (\c _ -> recursiveLookup remapping c) remapping filterEdges (a,b,_) = a `S.member` candidateNodes && b `S.member` candidateNodes - orderEdge (a,b,_) = if a < b then (a,b) else (b,a)- counter = foldl' (\map key -> M.insertWith (+) key 1 map) M.empty+ counter = M.fromListWith (+) . map (\key -> (key, 1)) isRegularEdge (_, _, CFEFlow) = True isRegularEdge _ = False @@ -316,11 +320,6 @@ Nothing -> node Just x -> recursiveLookup map x - isStructural (node, label) =- case label of- CFStructuralNode -> True- _ -> False- isLinear node = M.findWithDefault 0 node inDegree == 1 && M.findWithDefault 0 node outDegree == 1@@ -494,7 +493,7 @@ TA_Binary _ _ a b -> sequentially [a,b] TA_Expansion _ list -> sequentially list TA_Sequence _ list -> sequentially list- TA_Parentesis _ t -> build t+ TA_Parenthesis _ t -> build t TA_Trinary _ cond a b -> do condition <- build cond@@ -578,18 +577,11 @@ T_Array _ list -> sequentially list - T_Assignment {} -> buildAssignment DefaultScope t+ T_Assignment {} -> buildAssignment Nothing t - T_Backgrounded id body -> do- start <- newStructuralNode- fork <- subshell id "backgrounding '&'" $ build body- pid <- newNodeRange $ CFSetBackgroundPid id- status <- newNodeRange $ CFSetExitCode id+ T_Backgrounded id body -> buildBackground id "backgrounding '&'" body - linkRange start fork- -- Add a join from the fork to warn about variable changes- linkRangeAs CFEFalseFlow fork pid- linkRanges [start, pid, status]+ T_KshCoprocess id body -> buildBackground id "backgrounding '|&'" body T_Backticked id body -> subshell id "`..` expansion" $ sequentially body@@ -614,68 +606,72 @@ T_CaseExpression id t [] -> build t - T_CaseExpression id t list -> do+ T_CaseExpression id t list@(hd:tl) -> do start <- newStructuralNode- token <- build t- branches <- mapM buildBranch list end <- newStructuralNode+ token <- build t+ branches <- mapM (buildBranch end) (hd NE.:| tl) - let neighbors = zip branches $ tail branches- let (_, firstCond, _) = head branches- let (_, lastCond, lastBody) = last branches+ let neighbors = zip (NE.toList branches) $ (NE.tail branches ++ [(end, end, undefined, undefined)])+ let (firstCond, _, _, _) = NE.head branches linkRange start token linkRange token firstCond- mapM_ (uncurry $ linkBranch end) neighbors- linkRange lastBody end-- unless (any hasCatchAll list) $- -- There's no *) branch, so assume we can fall through- void $ linkRange token end+ mapM_ (uncurry linkBranch) neighbors return $ spanRange start end where+ buildBranch end (typ, cond, body) = do+ bodyNode <- sequentially body+ condNode <- buildCond bodyNode cond+ nextCondNode <- newStructuralNode+ nextBodyNode <- newStructuralNode+ case typ of+ CaseBreak -> linkRange bodyNode end+ CaseFallThrough -> linkRange bodyNode nextBodyNode+ CaseContinue -> linkRange bodyNode nextCondNode+ linkRange condNode nextCondNode+ return (condNode, bodyNode, nextCondNode, nextBodyNode)+ -- for a | b | c, evaluate each in turn and allow short circuiting- buildCond list = do- start <- newStructuralNode- conds <- mapM build list- end <- newStructuralNode- linkRanges (start:conds)- mapM_ (`linkRange` end) conds- return $ spanRange start end+ buildCond _ [] = newStructuralNode+ buildCond body (alt:rest) = do+ altNode <- build alt+ linkRange altNode body - buildBranch (typ, cond, body) = do- c <- buildCond cond- b <- sequentially body- linkRange c b- return (typ, c, b)+ let isCatchAll = fromMaybe False $ do+ pg <- wordToExactPseudoGlob alt+ return $ pg `pseudoGlobIsSuperSetof` [PGMany] - linkBranch end (typ, cond, body) (_, nextCond, nextBody) = do- -- Failure case- linkRange cond nextCond- -- After body- case typ of- CaseBreak -> linkRange body end- CaseFallThrough -> linkRange body nextBody- CaseContinue -> linkRange body nextCond+ nextNode <- buildCond body rest+ unless isCatchAll $+ void $ linkRange altNode nextNode - -- Find a *) if any+ return $ spanRange altNode nextNode - hasCatchAll (_,cond,_) = any isCatchAll cond- isCatchAll c = fromMaybe False $ do- pg <- wordToExactPseudoGlob c- return $ pg `pseudoGlobIsSuperSetof` [PGMany]+ linkBranch (cond, body, nextCond, nextBody) (cond2, body2, nextCond2, nextBody2) = do+ linkRange nextCond cond2+ linkRange nextBody body2 - T_Condition id _ op -> do++ T_Condition id _ _ op -> do cond <- build op status <- newNodeRange $ CFSetExitCode id linkRange cond status - T_CoProc id maybeName t -> do- let name = fromMaybe "COPROC" maybeName+ T_CoProc id maybeNameToken t -> do+ -- If unspecified, "COPROC". If not a constant string, Nothing.+ let maybeName = case maybeNameToken of+ Just x -> getLiteralString x+ Nothing -> Just "COPROC"++ let parentNode = case maybeName of+ Just str -> applySingle $ IdTagged id $ CFWriteVariable str CFValueArray+ Nothing -> CFStructuralNode+ start <- newStructuralNode- parent <- newNodeRange $ applySingle $ IdTagged id $ CFWriteVariable name CFValueArray+ parent <- newNodeRange parentNode child <- subshell id "coproc" $ build t end <- newNodeRange $ CFSetExitCode id @@ -712,6 +708,9 @@ linkRange totalRead result else return totalRead + T_DollarBraceCommandExpansion id _ body ->+ sequentially body+ T_DoubleQuoted _ list -> sequentially list T_DollarExpansion id body ->@@ -857,18 +856,26 @@ status <- newNodeRange (CFSetExitCode id) linkRange assignments status - T_SimpleCommand id vars list@(cmd:_) ->- handleCommand t vars list $ getUnquotedLiteral cmd+ T_SimpleCommand id vars (cmd:args) ->+ handleCommand t vars (cmd NE.:| args) $ getUnquotedLiteral cmd T_SingleQuoted _ _ -> none T_SourceCommand _ originalCommand inlinedSource -> do cmd <- build originalCommand- end <- newStructuralNode- inline <- withReturn end $ build inlinedSource- linkRange cmd inline- linkRange inline end- return $ spanRange cmd inline+ sourceAsBoundary <- reader $ cfSourceAsBoundary . cfParameters+ if sourceAsBoundary+ then+ -- Data-flow boundary: do not inline the sourced body into the CFG.+ -- Functions/vars it defines become opaque here; the file is+ -- analyzed on its own when it is itself an input.+ return cmd+ else do+ end <- newStructuralNode+ inline <- withReturn end $ build inlinedSource+ linkRange cmd inline+ linkRange inline end+ return $ spanRange cmd inline T_Subshell id body -> do main <- subshell id "explicit (..) subshell" $ sequentially body@@ -887,9 +894,22 @@ T_Less _ -> none T_ParamSubSpecialChar _ _ -> none - x -> error ("Unimplemented: " ++ show x)+ x -> do+ error ("Unimplemented: " ++ show x) -- STRIP+ none -- Still in `where` clause+ buildBackground id reason body = do+ start <- newStructuralNode+ fork <- subshell id reason $ build body+ pid <- newNodeRange $ CFSetBackgroundPid id+ status <- newNodeRange $ CFSetExitCode id++ linkRange start fork+ -- Add a join from the fork to warn about variable changes+ linkRangeAs CFEFalseFlow fork pid+ linkRanges [start, pid, status]+ forInHelper id name words body = do entry <- newStructuralNode expansion <- sequentially words@@ -919,17 +939,18 @@ linkRange condRange end -handleCommand cmd vars args literalCmd = do+handleCommand simpleCmdToken vars args literalCmd = do -- TODO: Handle assignments in declaring commands case literalCmd of- Just "exit" -> regularExpansion vars args $ handleExit- Just "return" -> regularExpansion vars args $ handleReturn+ Just "exit" -> regularExpansion vars (NE.toList args) $ handleExit+ Just "return" -> regularExpansion vars (NE.toList args) $ handleReturn Just "unset" -> regularExpansionWithStatus vars args $ handleUnset args Just "declare" -> handleDeclare args Just "local" -> handleDeclare args Just "typeset" -> handleDeclare args+ Just "readonly" -> handleDeclare args Just "printf" -> regularExpansionWithStatus vars args $ handlePrintf args Just "wait" -> regularExpansionWithStatus vars args $ handleWait args@@ -947,18 +968,18 @@ -- This will mostly behave like 'command' but ok Just "builtin" -> case args of- [_] -> regular- (_:newargs@(newcmd:_)) ->- handleCommand newcmd vars newargs $ getLiteralString newcmd+ _ NE.:| [] -> regular+ (_ NE.:| newcmd:newargs) ->+ handleCommand simpleCmdToken vars (newcmd NE.:| newargs) $ getLiteralString newcmd Just "command" -> case args of- [_] -> regular- (_:newargs@(newcmd:_)) ->- handleOthers (getId newcmd) vars newargs $ getLiteralString newcmd+ _ NE.:| [] -> regular+ (_ NE.:| newcmd:newargs) ->+ handleOthers (getId simpleCmdToken) vars (newcmd NE.:| newargs) $ getLiteralString newcmd _ -> regular where- regular = handleOthers (getId cmd) vars args literalCmd+ regular = handleOthers (getId simpleCmdToken) vars args literalCmd handleExit = do exitNode <- reader cfExitTarget case exitNode of@@ -982,7 +1003,7 @@ unreachable <- newNode CFUnreachable return $ Range ret unreachable - handleUnset (cmd:args) = do+ handleUnset (_ NE.:| args) = do case () of _ | "n" `elem` flagNames -> unsetWith CFUndefineNameref _ | "v" `elem` flagNames -> unsetWith CFUndefineVariable@@ -994,14 +1015,14 @@ (names, flags) = partition (null . fst) pairs flagNames = map fst flags literalNames :: [(Token, String)] -- Literal names to unset, e.g. [(myfuncToken, "myfunc")]- literalNames = mapMaybe (\(_, t) -> getLiteralString t >>= (return . (,) t)) names+ literalNames = mapMaybe (\(_, t) -> (,) t <$> getLiteralString t) names -- Apply a constructor like CFUndefineVariable to each literalName, and tag with its id unsetWith c = newNodeRange $ CFApplyEffects $ map (\(token, name) -> IdTagged (getId token) $ c name) literalNames variableAssignRegex = mkRegex "^([_a-zA-Z][_a-zA-Z0-9]*)=" - handleDeclare (cmd:args) = do+ handleDeclare (_ NE.:| args) = do isFunc <- asks cfIsFunction -- This is a bit of a kludge: we don't have great support for things like -- 'declare -i x=$x' so do one round with declare x=$x, followed by declare -i x@@ -1010,7 +1031,7 @@ assignments <- newNodeRange $ CFApplyEffects assignments addedProps <- if null added then newStructuralNode else newNodeRange $ CFApplyEffects added removedProps <- if null removed then newStructuralNode else newNodeRange $ CFApplyEffects removed- result <- newNodeRange $ CFSetExitCode (getId cmd)+ result <- newNodeRange $ CFSetExitCode (getId simpleCmdToken) linkRanges [before, assignments, addedProps, removedProps, result] where opts = map fst $ getGenericOpts args@@ -1020,23 +1041,28 @@ func = "f" `elem` opts || "F" `elem` opts global = "g" `elem` opts export = "x" `elem` opts+ -- 'readonly' is like 'declare -r', except it doesn't make variables local+ isReadonlyCommand = literalCmd == Just "readonly"+ readonly = "r" `elem` opts || isReadonlyCommand writer isFunc = case () of _ | global -> CFWriteGlobal- _ | isFunc -> CFWriteLocal+ _ | isFunc && not isReadonlyCommand -> CFWriteLocal _ -> CFWriteVariable scope isFunc = case () of- _ | global -> GlobalScope- _ | isFunc -> LocalScope- _ -> DefaultScope+ _ | global -> Just GlobalScope+ _ | isFunc && not isReadonlyCommand -> Just LocalScope+ _ -> Nothing addedProps = S.fromList $ concat $ [ [ CFVPArray | array ], [ CFVPInteger | integer ], [ CFVPExport | export ],- [ CFVPAssociative | associative ]+ [ CFVPAssociative | associative ],+ -- 'readonly -f' and 'declare -rf' apply to functions, not variables+ [ CFVPReadonly | readonly && not func ] ] removedProps = S.fromList $ concat $ [@@ -1058,7 +1084,7 @@ let id = getId t pre = [t]- literal = fromJust $ getLiteralStringExt (const $ Just "\0") t+ literal = getLiteralStringDef "\0" t isKnown = '\0' `notElem` literal match = fmap head $ variableAssignRegex `matchRegex` literal name = fromMaybe literal match@@ -1090,7 +1116,7 @@ in concatMap (drop 1) plusses - handlePrintf (cmd:args) =+ handlePrintf (_ NE.:| args) = newNodeRange $ CFApplyEffects $ maybeToList findVar where findVar = do@@ -1099,7 +1125,7 @@ name <- getLiteralString arg return $ IdTagged (getId arg) $ CFWriteVariable name CFValueString - handleWait (cmd:args) =+ handleWait (_ NE.:| args) = newNodeRange $ CFApplyEffects $ maybeToList findVar where findVar = do@@ -1108,11 +1134,11 @@ name <- getLiteralString arg return $ IdTagged (getId arg) $ CFWriteVariable name CFValueInteger - handleMapfile (cmd:args) =+ handleMapfile (_ NE.:| args) = newNodeRange $ CFApplyEffects [findVar] where findVar =- let (id, name) = fromMaybe (getId cmd, "MAPFILE") $ getFromArg `mplus` getFromFallback+ let (id, name) = fromMaybe (getId simpleCmdToken, "MAPFILE") $ getFromArg `mplus` getFromFallback in IdTagged id $ CFWriteVariable name CFValueArray getFromArg = do@@ -1128,7 +1154,7 @@ guard $ isVariableName name return (getId c, name) - handleRead (cmd:args) = newNodeRange $ CFApplyEffects main+ handleRead (_ NE.:| args) = newNodeRange $ CFApplyEffects main where main = fromMaybe fallback $ do flags <- getGnuOpts flagsForRead args@@ -1152,13 +1178,13 @@ fallback = let names = reverse $ map fromJust $ takeWhile isJust $ map (\c -> sequence (getId c, getLiteralString c)) $ reverse args- namesOrDefault = if null names then [(getId cmd, "REPLY")] else names+ namesOrDefault = if null names then [(getId simpleCmdToken, "REPLY")] else names hasDashA = any (== "a") $ map fst $ getGenericOpts args value = if hasDashA then CFValueArray else CFValueString in map (\(id, name) -> IdTagged id $ CFWriteVariable name value) namesOrDefault - handleDEFINE (cmd:args) =+ handleDEFINE (_ NE.:| args) = newNodeRange $ CFApplyEffects $ maybeToList findVar where findVar = do@@ -1167,15 +1193,15 @@ guard $ isVariableName str return $ IdTagged (getId name) $ CFWriteVariable str CFValueString - handleOthers id vars args cmd =- regularExpansion vars args $ do- exe <- newNodeRange $ CFExecuteCommand cmd+ handleOthers id vars args maybeName =+ regularExpansion vars (NE.toList args) $ do+ exe <- newNodeRange $ CFExecuteCommand maybeName status <- newNodeRange $ CFSetExitCode id linkRange exe status regularExpansion vars args p = do args <- sequentially args- assignments <- mapM (buildAssignment PrefixScope) vars+ assignments <- mapM (buildAssignment (Just PrefixScope)) vars exe <- p dropAssignments <- if null vars@@ -1187,15 +1213,15 @@ linkRanges $ [args] ++ assignments ++ [exe] ++ dropAssignments - regularExpansionWithStatus vars args@(cmd:_) p = do- initial <- regularExpansion vars args p- status <- newNodeRange $ CFSetExitCode (getId cmd)+ regularExpansionWithStatus vars args p = do+ initial <- regularExpansion vars (NE.toList args) p+ status <- newNodeRange $ CFSetExitCode (getId simpleCmdToken) linkRange initial status none = newStructuralNode -data Scope = DefaultScope | GlobalScope | LocalScope | PrefixScope+data Scope = GlobalScope | LocalScope | PrefixScope deriving (Eq, Ord, Show, Generic, NFData) buildAssignment scope t = do@@ -1209,10 +1235,10 @@ let valueType = if null indices then f id value else CFValueArray let scoper = case scope of- PrefixScope -> CFWritePrefix- LocalScope -> CFWriteLocal- GlobalScope -> CFWriteGlobal- DefaultScope -> CFWriteVariable+ Just PrefixScope -> CFWritePrefix+ Just LocalScope -> CFWriteLocal+ Just GlobalScope -> CFWriteGlobal+ Nothing -> CFWriteVariable write <- newNodeRange $ applySingle $ IdTagged id $ scoper var valueType linkRanges [expand, index, read, write] where@@ -1301,7 +1327,10 @@ reversed = grev withExitEdges postDoms = dom reversed mainexit (_, maxNode) = nodeRange graph- asArray = array (0, maxNode) postDoms+ -- Holes in the array cause "Exception: (Array.!): undefined array element" while+ -- inspecting/debugging, so fill the array first and then update.+ initializedArray = listArray (0, maxNode) $ repeat []+ asArray = initializedArray // postDoms return [] runTests = $( [| $(forAllProperties) (quickCheckWithResult (stdArgs { maxSuccess = 1 }) ) |])
src/ShellCheck/CFGAnalysis.hs view
@@ -20,7 +20,6 @@ {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE DeriveAnyClass, DeriveGeneric #-}-{-# LANGUAGE CPP #-} {- Data Flow Analysis on a Control Flow Graph.@@ -59,6 +58,9 @@ ,getIncomingState ,getOutgoingState ,doesPostDominate+ ,variableMayBeDeclaredInteger+ ,variableMayBeAssignedInteger+ ,variableMustBeDeclaredReadonly ,ShellCheck.CFGAnalysis.runTests -- STRIP ) where @@ -131,7 +133,7 @@ literalValue = Nothing } }- flatVars = M.unionsWith (\_ last -> last) $ map mapStorage [sGlobalValues s, sLocalValues s, sPrefixValues s]+ flatVars = M.unions $ map mapStorage [sPrefixValues s, sLocalValues s, sGlobalValues s] -- Conveniently get the state before a token id getIncomingState :: CFGAnalysis -> Id -> Maybe ProgramState@@ -153,6 +155,29 @@ (targetStart, _) <- M.lookup target $ tokenToRange analysis return $ targetStart `elem` (postDominators analysis ! baseEnd) +-- See if any execution path results in the variable containing a state+variableMayHaveState :: ProgramState -> String -> CFVariableProp -> Maybe Bool+variableMayHaveState state var property = do+ value <- M.lookup var $ variablesInScope state+ return $ any (S.member property) $ variableProperties value++-- See if every execution path results in the variable containing a state+variableMustHaveState :: ProgramState -> String -> CFVariableProp -> Maybe Bool+variableMustHaveState state var property = do+ value <- M.lookup var $ variablesInScope state+ return $ all (S.member property) $ variableProperties value++-- See if any execution path declares the variable an integer (declare -i).+variableMayBeDeclaredInteger state var = variableMayHaveState state var CFVPInteger++-- See if every execution path declares the variable readonly (readonly, declare -r).+variableMustBeDeclaredReadonly state var = variableMustHaveState state var CFVPReadonly++-- See if any execution path suggests the variable may contain an integer value+variableMayBeAssignedInteger state var = do+ value <- M.lookup var $ variablesInScope state+ return $ (numericalStatus $ variableValue value) >= NumericalStatusMaybe+ getDataForNode analysis node = M.lookup node $ nodeToData analysis -- The current state of data flow at a point in the program, potentially as a diff@@ -283,7 +308,6 @@ PrefixScope -> (sPrefixValues, insertPrefix) LocalScope -> (sLocalValues, insertLocal) GlobalScope -> (sGlobalValues, insertGlobal)- DefaultScope -> error $ pleaseReport "Unresolved scope in dependency" alreadyExists = isJust $ vmLookup name $ mapToCheck state in@@ -434,14 +458,6 @@ } deriving (Eq, Generic, NFData) -#if MIN_VERSION_deepseq(1,4,2)--- Our deepseq already has a STRef instance-#else--- Older deepseq (for GHC < 8) lacks this instance-instance NFData (STRef s a) where- rnf = (`seq` ())-#endif- -- Overwrite a base state with the contents of a diff state -- This is unrelated to join/merge. patchState :: InternalState -> InternalState -> InternalState@@ -657,7 +673,7 @@ _ | vmIsQuickEqual base diff -> diff _ -> VersionedMap { mapVersion = -1,- mapStorage = M.unionWith (flip const) (mapStorage base) (mapStorage diff)+ mapStorage = M.union (mapStorage diff) (mapStorage base) } -- Set a variable. This includes properties. Applies it to the appropriate scope.@@ -814,7 +830,7 @@ f (s:rest) = do -- Go up the stack until we find the value, and add -- a dependency on each state (including where it was found)- res <- fromMaybe (f rest) (return <$> get (stackState s) key)+ res <- maybe (f rest) return (get (stackState s) key) modifySTRef (dependencies s) $ S.insert $ dep key res return res @@ -1104,34 +1120,34 @@ CFSetProps scope name props -> case scope of- DefaultScope -> do+ Nothing -> do state <- readVariable ctx name writeVariable ctx name $ addProperties props state- GlobalScope -> do+ Just GlobalScope -> do state <- readGlobal ctx name writeGlobal ctx name $ addProperties props state- LocalScope -> do+ Just LocalScope -> do out <- readSTRef (cOutput ctx) state <- readLocal ctx name writeLocal ctx name $ addProperties props state- PrefixScope -> do+ Just PrefixScope -> do -- Prefix values become local state <- readLocal ctx name writeLocal ctx name $ addProperties props state CFUnsetProps scope name props -> case scope of- DefaultScope -> do+ Nothing -> do state <- readVariable ctx name writeVariable ctx name $ removeProperties props state- GlobalScope -> do+ Just GlobalScope -> do state <- readGlobal ctx name writeGlobal ctx name $ removeProperties props state- LocalScope -> do+ Just LocalScope -> do out <- readSTRef (cOutput ctx) state <- readLocal ctx name writeLocal ctx name $ removeProperties props state- PrefixScope -> do+ Just PrefixScope -> do -- Prefix values become local state <- readLocal ctx name writeLocal ctx name $ removeProperties props state@@ -1271,7 +1287,7 @@ else do let (next, rest) = S.deleteFindMin ps nexts <- process states next- writeSTRef pending $ foldl (flip S.insert) rest nexts+ writeSTRef pending $ S.union (S.fromList nexts) rest f (n-1) pending states process states node = do@@ -1335,7 +1351,7 @@ -- All nodes we've touched invocations <- readSTRef $ cInvocations ctx- let invokedNodes = M.fromDistinctAscList $ map (\c -> (c, ())) $ S.toList $ M.keysSet $ groupByNode $ M.map snd invocations+ let invokedNodes = M.fromSet (const ()) $ S.unions $ map (M.keysSet . snd) $ M.elems invocations -- Invoke all functions that were declared but not invoked -- This is so that we still get warnings for dead code@@ -1358,7 +1374,7 @@ -- Fill in the map with unreachable states for anything we didn't get to let baseStates = M.fromDistinctAscList $ map (\c -> (c, (unreachableState, unreachableState))) $ uncurry enumFromTo $ nodeRange $ cfGraph cfg- let allStates = M.unionWith (flip const) baseStates invokedStates+ let allStates = M.union invokedStates baseStates -- Convert to external states let nodeToData = M.map (\(a,b) -> (internalToExternal a, internalToExternal b)) allStates
src/ShellCheck/Checker.hs view
@@ -22,9 +22,12 @@ import ShellCheck.Analyzer import ShellCheck.ASTLib+import ShellCheck.Data (shellFromFilename)+import ShellCheck.EditorConfig import ShellCheck.Interface import ShellCheck.Parser +import Debug.Trace -- DO NOT SUBMIT import Data.Either import Data.Functor import Data.List@@ -49,17 +52,6 @@ where fail = error "Internal shellcheck error: id doesn't exist. Please report!" -shellFromFilename filename = listToMaybe candidates- where- shellExtensions = [(".ksh", Ksh)- ,(".bash", Bash)- ,(".bats", Bash)- ,(".dash", Dash)]- -- The `.sh` is too generic to determine the shell:- -- We fallback to Bash in this case and emit SC2148 if there is no shebang- candidates =- [sh | (ext,sh) <- shellExtensions, ext `isSuffixOf` filename]- checkScript :: Monad m => SystemInterface m -> CheckSpec -> m CheckResult checkScript sys spec = do results <- checkScript (csScript spec)@@ -86,6 +78,7 @@ asCheckSourced = csCheckSourced spec, asExecutionMode = Executed, asTokenPositions = tokenPositions,+ asExtendedAnalysis = csExtendedAnalysis spec, asOptionalChecks = getEnableDirectives root ++ csOptionalChecks spec } where as = newAnalysisSpec root let analysisMessages =@@ -162,8 +155,92 @@ siFindSource = mapper } +-- shellcheck.* directives extracted from an EditorConfig file are merged+-- into the same "key=value" blob as .shellcheckrc. We simulate that here+-- by feeding editorConfigDirectives' output through siGetConfig.+checkWithEditorConfig ec name src =+ let sys = (mockedSystemInterface [("foo", src)]) {+ siGetConfig = const . return $+ Just (".editorconfig", fromMaybe "" $ editorConfigDirectives ec name)+ }+ in getErrors sys emptyCheckSpec {+ csScript = src,+ csExcludedWarnings = [2148]+ }++prop_editorConfigAppliesKnownShell =+ null $ checkWithEditorConfig "[foo]\nshellcheck.shell=bash\n" "foo"+ "#!/bin/sh\necho \"hi\""+prop_editorConfigAppliesDisable =+ null $ checkWithEditorConfig "[foo]\nshellcheck.disable=SC2086\n" "foo"+ "#!/bin/sh\necho $1"+prop_editorConfigUnknownShellIsReported =+ -- An unknown shell can't be applied silently; it surfaces as a+ -- config parse error (SC1134) rather than being dropped.+ [1134] == checkWithEditorConfig "[foo]\nshellcheck.shell=zsh\n" "foo"+ "#!/bin/sh\necho \"hi\""+prop_editorConfigCommentValueIsReported =+ -- EditorConfig has no inline comments, so a '#'-prefixed value is+ -- reported as a config error (SC1134) instead of being eaten.+ [1134] == checkWithEditorConfig "[foo]\nshellcheck.disable=#abc\n" "foo"+ "#!/bin/sh\necho \"hi\""+prop_editorConfigNonMatchingSectionIgnored =+ -- A directive in a section whose glob does not match the file is+ -- not applied (and produces no config error).+ [2086] == checkWithEditorConfig "[bar]\nshellcheck.disable=SC2086\n" "foo"+ "#!/bin/sh\necho $1"+ prop_findsParseIssue = check "echo \"$12\"" == [1037] +prop_kshCoprocessRead =+ null $ check "#!/bin/ksh\nprintf '%s\\n' data |&\nread -pr record\nprintf '%s\\n' \"$record\""++prop_kshCoprocessReadWithoutSpaces =+ null $ check "#!/bin/ksh\nprintf '%s\\n' data|&read -r record <&p\nprintf '%s\\n' \"$record\""++prop_kshCoprocessAssignmentScope =+ [2030, 2031] == check "#!/bin/ksh\nvalue=parent\nvalue=child && : |&\nwait \"$!\"\nprintf '%s\\n' \"$value\""++prop_kshCoprocessEof = null $ check "#!/bin/ksh\ntrue|&"++prop_kshCoprocessFilename =+ null $ checkWithSpec [] emptyCheckSpec {+ csFilename = "example.ksh",+ csScript = "true|&"+ }++prop_kshCoprocessDirective =+ null $ check "#!/bin/bash\n#shellcheck shell=ksh\ntrue|&"++prop_kshCoprocessRc =+ null $ checkWithRc "shell=ksh\n" emptyCheckSpec {+ csScript = "#!/bin/bash\ntrue|&"+ }++prop_kshCoprocessDirectiveOverridesRc =+ null $ checkWithRc "shell=bash\n" emptyCheckSpec {+ csScript = "#!/bin/bash\n#shellcheck shell=ksh\ntrue|&"+ }++prop_kshCoprocessOverride =+ null $ checkWithSpec [] emptyCheckSpec {+ csShellTypeOverride = Just Ksh,+ csScript = "#!/bin/bash\ntrue|&"+ }++prop_kshCoprocessInSourcedCode =+ null $ checkWithIncludes [("helper", "#!/bin/bash\ntrue |&")] "#!/bin/ksh\n. helper"++prop_bashStderrPipe = null $ check "#!/bin/bash\nprintf '%s\\n' data |&\ncat"++prop_bashOverrideKeepsStderrPipe =+ [1072] == checkWithSpec [] emptyCheckSpec {+ csShellTypeOverride = Just Bash,+ csScript = "#!/bin/ksh\n#shellcheck shell=ksh\ntrue|&"+ }++prop_shStderrPipe = check "#!/bin/sh\nprintf '%s\\n' data |& cat" == [3029]+ prop_commentDisablesParseIssue1 = null $ check "#shellcheck disable=SC1037\necho \"$12\"" prop_commentDisablesParseIssue2 =@@ -219,6 +296,9 @@ prop_worksWhenSourcingWithDashDash = null $ checkWithIncludes [("lib", "bar=1")] "source -- lib; echo \"$bar\"" +prop_worksWhenSourcingWithDashP =+ null $ checkWithIncludes [("lib", "bar=1")] "source -p \"$MYPATH\" lib; echo \"$bar\""+ prop_worksWhenDotting = null $ checkWithIncludes [("lib", "bar=1")] ". lib; echo \"$bar\"" @@ -303,6 +383,13 @@ csScript = "(( 3.14 ))" } +prop_deducesTypeFromEnvrcExtension = result == [2079]+ where+ result = checkWithSpec [] emptyCheckSpec {+ csFilename = ".envrc",+ csScript = "(( 3.14 ))"+ }+ prop_canDisableShebangWarning = null $ result where result = checkWithSpec [] emptyCheckSpec {@@ -310,6 +397,56 @@ csScript = "#shellcheck disable=SC2148\nfoo" } +prop_warnsButIgnoresLeadingCommentWithFilename = [1113, 2148] == result+ where+ result = checkWithSpec [] emptyCheckSpec {+ csFilename = "file.sh",+ csScript = "# /usr/bin/python is an interpreter\n/usr/bin/python \"$@\""+ }++prop_canIgnoreLeadingFormatWarning1 = [2148] == result+ where+ result = checkWithSpec [] emptyCheckSpec {+ csFilename = "file.sh",+ csScript = "# /usr/bin/python is an interpreter\n# shellcheck disable=SC1113\n/usr/bin/python \"$@\""+ }++-- This technically avoids the warning, but either way+prop_canIgnoreLeadingFormatWarning2 = [2148] == result+ where+ result = checkWithSpec [] emptyCheckSpec {+ csFilename = "file.sh",+ csScript = "# shellcheck disable=SC1113\n# /usr/bin/python is an interpreter\n/usr/bin/python \"$@\""+ }++prop_canIgnoreLeadingFormatWarning3 = null result+ where+ result = checkWithSpec [] emptyCheckSpec {+ csFilename = "file.sh",+ csScript = "# /etc/profile -- Shell Initialization\n# shellcheck disable=SC1113 shell=sh\nVAR=VALUE\nexport VAR\n"+ }++prop_onlyFirstLineCanTriggerMissingBangWarning = [2148] == result+ where+ result = checkWithSpec [] emptyCheckSpec {+ csFilename = "file.sh",+ csScript = "# shell init file\n# /etc/profile is my name and init is my game\n echo 'Hello World' >&2\n"+ }++prop_bangInLeadingCommentIsNotShebang = [2086] == result+ where+ result = checkWithSpec [] emptyCheckSpec {+ csFilename = "file.bash",+ csScript = "# Notes:\n# ! python is needed for the helper\necho $1\n"+ }++prop_stillWarnsAboutSpacedShebangAfterComment = [1115, 1128] == result+ where+ result = checkWithSpec [] emptyCheckSpec {+ csFilename = "file.sh",+ csScript = "# Copyright\n# !/bin/sh\necho b\n"+ }+ prop_canDisableAllWarnings = result == [2086] where result = checkWithSpec [] emptyCheckSpec {@@ -339,6 +476,14 @@ csCheckSourced = True } +prop_sourcedCommandInExpansionDoesntCrash = result == [2034]+ where+ result = checkWithSpec [("lib.sh", "echo hello")] emptyCheckSpec {+ csFilename = "file.bash",+ csScript = "x=$(source lib.sh)",+ csCheckSourced = True+ }+ prop_canEnableOptionalsWithSpec = result == [2244] where result = checkWithSpec [] emptyCheckSpec {@@ -392,6 +537,13 @@ csIgnoreRC = False } +prop_unknownRcDirectiveGetsWarning = result == [1107, 2086]+ where+ result = checkWithRc "foo=bar" emptyCheckSpec {+ csScript = "#!/bin/sh\necho $1",+ csIgnoreRC = False+ }+ prop_canEnableOptionalsWithRc = result == [2244] where result = checkWithRc "enable=avoid-nullary-conditions" emptyCheckSpec {@@ -506,6 +658,89 @@ where result = checkWithRc "disable=1104" emptyCheckSpec { csScript = "!/bin/bash\necho 'hello world'"+ }++prop_sourceWithHereDocWorks = null result+ where+ result = checkWithIncludes [("bar", "true\n")] "source bar << eof\nlol\neof"++prop_hereDocsAreParsedWithoutTrailingLinefeed = 1044 `elem` result+ where+ result = check "cat << eof"++prop_hereDocsWillHaveParsedIndices = null result+ where+ result = check "#!/bin/bash\nmy_array=(a b)\ncat <<EOF >> ./test\n $(( 1 + my_array[1] ))\nEOF"++prop_rcCanSuppressDfa = null result+ where+ result = checkWithRc "extended-analysis=false" emptyCheckSpec {+ csScript = "#!/bin/sh\nexit; foo;"+ }++prop_fileCanSuppressDfa = null $ traceShowId result+ where+ result = checkWithRc "" emptyCheckSpec {+ csScript = "#!/bin/sh\n# shellcheck extended-analysis=false\nexit; foo;"+ }++prop_fileWinsWhenSuppressingDfa1 = null result+ where+ result = checkWithRc "extended-analysis=true" emptyCheckSpec {+ csScript = "#!/bin/sh\n# shellcheck extended-analysis=false\nexit; foo;"+ }++prop_fileWinsWhenSuppressingDfa2 = result == [2317]+ where+ result = checkWithRc "extended-analysis=false" emptyCheckSpec {+ csScript = "#!/bin/sh\n# shellcheck extended-analysis=true\nexit; foo;"+ }++prop_flagWinsWhenSuppressingDfa1 = result == [2317]+ where+ result = checkWithRc "extended-analysis=false" emptyCheckSpec {+ csScript = "#!/bin/sh\n# shellcheck extended-analysis=none\nexit; foo;",+ csExtendedAnalysis = Just ExtendedAnalysisFull+ }++prop_flagWinsWhenSuppressingDfa2 = null result+ where+ result = checkWithRc "extended-analysis=true" emptyCheckSpec {+ csScript = "#!/bin/sh\n# shellcheck extended-analysis=full\nexit; foo;",+ csExtendedAnalysis = Just ExtendedAnalysisNone+ }++-- 'local' still does data-flow analysis within a file...+prop_localKeepsIntraFileDfa = 2317 `elem` result+ where+ result = getErrors (mockedSystemInterface []) emptyCheckSpec {+ csScript = "#!/bin/sh\nexit; foo;",+ csExtendedAnalysis = Just ExtendedAnalysisLocal+ }++-- ...but treats sourced files as boundaries, so it does not use data flow+-- from a sourced file (here: that f() always exits) the way 'full' does.+prop_localTreatsSourcesAsBoundary = 2317 `notElem` result+ where+ result = getErrors (mockedSystemInterface [("lib", "f() { exit 1; }")]) emptyCheckSpec {+ csScript = "#!/bin/sh\nsource lib\nf\nfoo",+ csCheckSourced = True,+ csExtendedAnalysis = Just ExtendedAnalysisLocal+ }++prop_localDirectiveTreatsSourcesAsBoundary = 2317 `notElem` result+ where+ result = getErrors (mockedSystemInterface [("lib", "f() { exit 1; }")]) emptyCheckSpec {+ csScript = "#!/bin/sh\n# shellcheck extended-analysis=local\nsource lib\nf\nfoo",+ csCheckSourced = True+ }++prop_fullFollowsDataFlowIntoSources = 2317 `elem` result+ where+ result = getErrors (mockedSystemInterface [("lib", "f() { exit 1; }")]) emptyCheckSpec {+ csScript = "#!/bin/sh\nsource lib\nf\nfoo",+ csCheckSourced = True,+ csExtendedAnalysis = Just ExtendedAnalysisFull } return []
src/ShellCheck/Checks/Commands.hs view
@@ -20,6 +20,7 @@ {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiWayIf #-}+{-# LANGUAGE PatternGuards #-} -- This module contains checks that examine specific commands by name. module ShellCheck.Checks.Commands (checker, optionalChecks, ShellCheck.Checks.Commands.runTests) where@@ -42,6 +43,7 @@ import qualified Data.Graph.Inductive.Graph as G import Data.List import Data.Maybe+import qualified Data.List.NonEmpty as NE import qualified Data.Map.Strict as M import qualified Data.Set as S import Test.QuickCheck.All (forAllProperties)@@ -60,6 +62,9 @@ verify f s = producesComments (getChecker [f]) s == Just True verifyNot f s = producesComments (getChecker [f]) s == Just False +verifyCodes :: CommandCheck -> String -> [Integer] -> Bool+verifyCodes f s c = runAndGetCodes (getChecker [f]) s == Just c+ commandChecks :: [CommandCheck] commandChecks = [ checkTr@@ -97,18 +102,21 @@ ,checkMvArguments, checkCpArguments, checkLnArguments ,checkFindRedirections ,checkReadExpansions- ,checkSudoRedirect- ,checkSudoArgs ,checkSourceArgs ,checkChmodDashr ,checkXargsDashi ,checkUnquotedEchoSpaces ,checkEvalArray+ ,checkGrepSendsPipefail+ ,checkEgrepSendsPipefail+ ,checkFgrepSendsPipefail ] ++ map checkArgComparison ("alias" : declaringCommands) ++ map checkMaskedReturns declaringCommands ++ map checkMultipleDeclaring declaringCommands ++ map checkBackreferencingDeclaration declaringCommands+ ++ map checkSudoArgs privilegeElevationCommands+ ++ map checkSudoRedirect privilegeElevationCommands optionalChecks = map fst optionalCommandChecks@@ -116,6 +124,7 @@ optionalCommandChecks = [ (newCheckDescription { cdName = "deprecate-which",+ cdId = [2230], cdDescription = "Suggest 'command -v' instead of 'which'", cdPositive = "which javac", cdNegative = "command -v javac"@@ -126,7 +135,7 @@ prop_verifyOptionalExamples = all check optionalCommandChecks where check (desc, check) =- verify check (cdPositive desc)+ runAndGetCodes (getChecker [check]) (cdPositive desc) == Just (cdId desc) && verifyNot check (cdNegative desc) -- Run a check against the getopt parser. If it fails, the lists are empty.@@ -181,16 +190,15 @@ checkCommand map t@(T_SimpleCommand id cmdPrefix (cmd:rest)) = sequence_ $ do name <- getLiteralString cmd return $- if '/' `elem` name- then- M.findWithDefault nullCheck (Basename $ basename name) map t- else if name == "builtin" && not (null rest) then- let t' = T_SimpleCommand id cmdPrefix rest- selectedBuiltin = fromMaybe "" $ getLiteralString . head $ rest- in M.findWithDefault nullCheck (Exactly selectedBuiltin) map t'- else do- M.findWithDefault nullCheck (Exactly name) map t- M.findWithDefault nullCheck (Basename name) map t+ if | '/' `elem` name ->+ M.findWithDefault nullCheck (Basename $ basename name) map t+ | name == "builtin", (h:_) <- rest ->+ let t' = T_SimpleCommand id cmdPrefix rest+ selectedBuiltin = onlyLiteralString h+ in M.findWithDefault nullCheck (Exactly selectedBuiltin) map t'+ | otherwise -> do+ M.findWithDefault nullCheck (Exactly name) map t+ M.findWithDefault nullCheck (Basename name) map t where basename = reverse . takeWhile (/= '/') . reverse@@ -299,7 +307,7 @@ "'expr' expects 3+ arguments but sees 1. Make sure each operator/operand is a separate argument, and escape <>&|." [first, second] |- (fromMaybe "" $ getLiteralString first) /= "length"+ onlyLiteralString first /= "length" && not (willSplit first || willSplit second) -> do checkOp first warn (getId t) 2307@@ -399,10 +407,88 @@ contra = mkRegex "[^a-zA-Z1-9]\\*|[][^$+\\\\]" +prop_checkGrepSendsPipefail1 = verify checkGrepSendsPipefail "set -o pipefail; cat file | grep -q pattern"+prop_checkGrepSendsPipefail2 = verify checkGrepSendsPipefail "set -o pipefail; cat file | grep --quiet pattern"+prop_checkGrepSendsPipefail3 = verify checkGrepSendsPipefail "set -o pipefail; cat file | grep -iq pattern"+prop_checkGrepSendsPipefail4 = verify checkGrepSendsPipefail "set -o pipefail; cmd1 | cmd2 | grep -q pattern"+prop_checkGrepSendsPipefail5 = verify checkGrepSendsPipefail "set -euo pipefail; cmd | grep -q foo"+prop_checkGrepSendsPipefail6 = verify checkGrepSendsPipefail "set -o pipefail; if cmd | grep -m 2 foo | cmd2; then true; fi"+prop_checkGrepSendsPipefail7 = verify checkGrepSendsPipefail "set -e -o pipefail; cmd | grep -L foo | cmd2"++prop_checkGrepSendsPipefailN1 = verifyNot checkGrepSendsPipefail "cat file | grep -q pattern"+prop_checkGrepSendsPipefailN2 = verifyNot checkGrepSendsPipefail "set -o pipefail; grep -q pattern file"+prop_checkGrepSendsPipefailN3 = verifyNot checkGrepSendsPipefail "set -o pipefail; cat file | grep pattern"+prop_checkGrepSendsPipefailN4 = verifyNot checkGrepSendsPipefail "set -o pipefail; grep -q pattern | cat"+prop_checkGrepSendsPipefailN5 = verifyNot checkGrepSendsPipefail "grep -q pattern file"+prop_checkGrepSendsPipefailN6 = verifyNot checkGrepSendsPipefail "set -o pipefail; cmd1 | bash -c 'grep -q pattern file'"+prop_checkGrepSendsPipefailN7 = verifyNot checkGrepSendsPipefail "set -o pipefail; cmd1 | grep -e -q"+prop_checkGrepSendsPipefailN8 = verifyNot checkGrepSendsPipefail "set -o pipefail; cmd1 | grep -eq pattern"+prop_checkGrepSendsPipefailN9 = verifyNot checkGrepSendsPipefail "set -o pipefail; cmd1 | grep --regexp -q"+prop_checkGrepSendsPipefailN10 = verifyNot checkGrepSendsPipefail "set -o pipefail; cmd1 | grep -- -q"+prop_checkGrepSendsPipefailN11 = verifyNot checkGrepSendsPipefail "set -o pipefail; cmd | grep -m 2 foo | cmd2"++checkGrepSendsPipefail = CommandCheck (Basename "grep") checkGrepSendsPipefailImpl++prop_checkEgrepSendsPipefail1 = verify checkEgrepSendsPipefail "set -o pipefail; cat file | egrep -q pattern"+checkEgrepSendsPipefail = CommandCheck (Basename "egrep") checkGrepSendsPipefailImpl++prop_checkFgrepSendsPipefail1 = verify checkFgrepSendsPipefail "set -o pipefail; cat file | fgrep -q pattern"+checkFgrepSendsPipefail = CommandCheck (Basename "fgrep") checkGrepSendsPipefailImpl++-- Catches occurrences of "grep -q" and variants, such as "-m" or "-L", inside of pipes under pipefail.+checkGrepSendsPipefailImpl cmd = do+ pipefail <- asks hasPipefail+ errexit <- asks hasErrexit+ astPath <- getPathM cmd+ sequence_ $ do+ guard pipefail+ opts <- map fst <$> parseGrepOpts (arguments cmd)+ let isQuiet = any (`elem` quietFlags) opts+ let isEarlyExit = isQuiet || any (`elem` earlyExitFlags) opts+ guard $ isEarlyExit+ _simpleCmd:grepRedirectingCmd:parentNodes <- Just $ NE.toList astPath+ T_Pipeline _ _ (_first:redirectingCmds) <- listToMaybe parentNodes+ guard $ any (\node -> getId node == getId grepRedirectingCmd) redirectingCmds+ guard $ isQuiet || errexit || isCondition (grepRedirectingCmd NE.:| parentNodes)+ return $ warn (getId cmd) 2337 warnMsg+ where+ -- Contains "L", even though BSD grep does not exit early with this flag,+ -- but GNU grep does. This is consistent with the linter practice of warning+ -- about potential problems, while also allowing users to disable specific+ -- linter checks locally.+ quietFlags = ["q", "quiet", "--silent"]+ earlyExitFlags = ["m", "max-count", "L"]+ parseGrepOpts = getOpts (True, True)+ "cilLnoqsvwxhHrRbaEFGPe:f:m:A:B:C:d:D:"+ (map (\name -> (name, True)) longOptionsConsumingParameter)+ longOptionsConsumingParameter =+ ["regexp", "file", "max-count", "after-context", "before-context",+ "context", "directories", "devices"]+ warnMsg = "In pipefail mode, the exit code of grep -q/-m/-L is subject to a race. " +++ "Use a non-pipe input like '< <(cmd)' or '<<<' instead."++ prop_checkTrapQuotes1 = verify checkTrapQuotes "trap \"echo $num\" INT" prop_checkTrapQuotes1a = verify checkTrapQuotes "trap \"echo `ls`\" INT" prop_checkTrapQuotes2 = verifyNot checkTrapQuotes "trap 'echo $num' INT" prop_checkTrapQuotes3 = verify checkTrapQuotes "trap \"echo $((1+num))\" EXIT DEBUG"+prop_checkTrapQuotes4 = verifyNot checkTrapQuotes "readonly num; trap \"echo $num\" INT"+prop_checkTrapQuotes5 = verifyNot checkTrapQuotes "num=1; readonly num; trap \"echo ${num}\" INT"+prop_checkTrapQuotes6 = verifyNot checkTrapQuotes "declare -r num=1; trap \"echo $num\" INT"+prop_checkTrapQuotes7 = verifyNot checkTrapQuotes "typeset -r num=1; trap \"echo $num\" INT"+prop_checkTrapQuotes8 = verify checkTrapQuotes "trap \"echo $num\" INT; readonly num"+prop_checkTrapQuotes9 = verify checkTrapQuotes "declare num=1; trap \"echo $num\" INT"+prop_checkTrapQuotes10 = verifyNot checkTrapQuotes "f() { readonly num=1; }; f; trap \"echo $num\" ERR"+prop_checkTrapQuotes11 = verify checkTrapQuotes "readonly num; f() { local num; trap \"echo $num\" ERR; }"+prop_checkTrapQuotes12 = verifyNot checkTrapQuotes "f() { local -r num; trap \"echo $num\" ERR; }"+prop_checkTrapQuotes13 = verify checkTrapQuotes "readonly num; trap \"echo $num $other\" ERR"+prop_checkTrapQuotes14 = verify checkTrapQuotes "[ \"$1\" ] && readonly num; trap \"echo $num\" ERR"+prop_checkTrapQuotes15 = verifyNot checkTrapQuotes "if [ \"$1\" ]; then readonly num=1; else readonly num=2; fi; trap \"echo $num\" ERR"+prop_checkTrapQuotes16 = verify checkTrapQuotes "f() { readonly num=1; }; trap \"echo $num\" ERR"+prop_checkTrapQuotes17 = verify checkTrapQuotes "readonly -f num; trap \"echo $num\" ERR"+prop_checkTrapQuotes18 = verifyNot checkTrapQuotes "builtin readonly num; trap \"echo $num\" ERR"+prop_checkTrapQuotes19 = verify checkTrapQuotes "f() { local -r num; }; f; trap \"echo $num\" ERR"+prop_checkTrapQuotes20 = verifyNot checkTrapQuotes "f() { declare -gr num; }; f; trap \"echo $num\" ERR" checkTrapQuotes = CommandCheck (Exactly "trap") (f . arguments) where f (x:_) = checkTrap x f _ = return ()@@ -411,11 +497,22 @@ warning id = warn id 2064 "Use single quotes, otherwise this expands now rather than when signalled." checkExpansions (T_DollarExpansion id _) = warning id checkExpansions (T_Backticked id _) = warning id- checkExpansions (T_DollarBraced id _ _) = warning id+ checkExpansions (T_DollarBraced id _ word) = do+ params <- ask+ let name = concat $ oversimplify word+ unless (isVariableName name && isReadonly params id name) $+ warning id checkExpansions (T_DollarArithmetic id _) = warning id checkExpansions _ = return () + -- A readonly variable can never change value, so it doesn't matter+ -- whether it's expanded now or when the trap runs.+ isReadonly params id name = fromMaybe False $ do+ cfga <- cfgAnalysis params+ state <- CF.getIncomingState cfga id+ CF.variableMustBeDeclaredReadonly state name + prop_checkReturn1 = verifyNot checkReturn "return" prop_checkReturn2 = verifyNot checkReturn "return 1" prop_checkReturn3 = verifyNot checkReturn "return $var"@@ -423,9 +520,31 @@ prop_checkReturn5 = verify checkReturn "return -1" prop_checkReturn6 = verify checkReturn "return 1000" prop_checkReturn7 = verify checkReturn "return 'hello world'"-checkReturn = CommandCheck (Exactly "return") (returnOrExit- (\c -> err c 2151 "Only one integer 0-255 can be returned. Use stdout for other data.")- (\c -> err c 2152 "Can only return 0-255. Other data should be written to stdout."))+-- Return a safe value.+prop_checkReturn8A = verifyCodes checkReturn "#!/bin/sh\nf() { return 0; }; f" []+prop_checkReturn8B = verifyCodes checkReturn "#!/bin/bash\nf() { return 0; }; f" []+prop_checkReturn8C = verifyCodes checkReturn "#!/bin/dash\nf() { return 0; }; f" []+prop_checkReturn8D = verifyCodes checkReturn "#!/bin/ksh\nf() { return 0; }; f" []+prop_checkReturn8E = verifyCodes checkReturn "#!/bin/busybox sh\nf() { return 0; }; f" []+-- Return not-a-number. Not supported on any shell, but bash treats it as 2, ksh as 0, the rest error.+prop_checkReturn9A = verifyCodes checkReturn "#!/bin/sh\nf() { return asdf; }; f" [2152]+prop_checkReturn9B = verifyCodes checkReturn "#!/bin/bash\nf() { return asdf; }; f" [2152]+prop_checkReturn9C = verifyCodes checkReturn "#!/bin/dash\nf() { return asdf; }; f" [2152]+prop_checkReturn9D = verifyCodes checkReturn "#!/bin/ksh\nf() { return asdf; }; f" [2152]+prop_checkReturn9E = verifyCodes checkReturn "#!/bin/busybox sh\nf() { return asdf; }; f" [2152]+-- Return negative. Dash and Busybox error, bash wraps, ksh allows.+prop_checkReturn10A = verifyCodes checkReturn "#!/bin/sh\nf() { return -1; }; f" [3426]+prop_checkReturn10B = verifyCodes checkReturn "#!/bin/bash\nf() { return -1; }; f" [2341]+prop_checkReturn10C = verifyCodes checkReturn "#!/bin/dash\nf() { return -1; }; f" [2339]+prop_checkReturn10D = verifyCodes checkReturn "#!/bin/ksh\nf() { return -1; }; f" []+prop_checkReturn10E = verifyCodes checkReturn "#!/bin/busybox sh\nf() { return -1; }; f" [2339]+-- Return out-of-bounds. Bash and Busybox error, bash wraps, dash and ksh allows.+prop_checkReturn11A = verifyCodes checkReturn "#!/bin/sh\nf() { return 1000; }; f" [3426]+prop_checkReturn11B = verifyCodes checkReturn "#!/bin/bash\nf() { return 1000; }; f" [2341]+prop_checkReturn11C = verifyCodes checkReturn "#!/bin/dash\nf() { return 1000; }; f" []+prop_checkReturn11D = verifyCodes checkReturn "#!/bin/ksh\nf() { return 1000; }; f" []+prop_checkReturn11E = verifyCodes checkReturn "#!/bin/busybox sh\nf() { return 1000; }; f" [2341]+checkReturn = CommandCheck (Exactly "return") (returnOrExit False) prop_checkExit1 = verifyNot checkExit "exit" prop_checkExit2 = verifyNot checkExit "exit 1"@@ -434,22 +553,77 @@ prop_checkExit5 = verify checkExit "exit -1" prop_checkExit6 = verify checkExit "exit 1000" prop_checkExit7 = verify checkExit "exit 'hello world'"-checkExit = CommandCheck (Exactly "exit") (returnOrExit- (\c -> err c 2241 "The exit status can only be one integer 0-255. Use stdout for other data.")- (\c -> err c 2242 "Can only exit with status 0-255. Other data should be written to stdout/stderr."))+-- Exit with a safe value.+prop_checkExit8A = verifyCodes checkExit "#!/bin/sh\nexit 0" []+prop_checkExit8B = verifyCodes checkExit "#!/bin/bash\nexit 0" []+prop_checkExit8C = verifyCodes checkExit "#!/bin/dash\nexit 0" []+prop_checkExit8D = verifyCodes checkExit "#!/bin/ksh\nexit 0" []+prop_checkExit8E = verifyCodes checkExit "#!/bin/busybox sh\nexit 0" []+-- Exit not-a-number. Not supported on any shell, but ksh treats it as 0.+prop_checkExit9A = verifyCodes checkExit "#!/bin/sh\nexit asdf" [2242]+prop_checkExit9B = verifyCodes checkExit "#!/bin/bash\nexit asdf" [2242]+prop_checkExit9C = verifyCodes checkExit "#!/bin/dash\nexit asdf" [2242]+prop_checkExit9D = verifyCodes checkExit "#!/bin/ksh\nexit adsf" [2242]+prop_checkExit9E = verifyCodes checkExit "#!/bin/busybox sh\nexit asdf" [2242]+-- Exit negative. Dash and Busybox error. Bash and Ksh wrap.+prop_checkExit10A = verifyCodes checkExit "#!/bin/sh\nexit -1" [3426]+prop_checkExit10B = verifyCodes checkExit "#!/bin/bash\nexit -1" [2340]+prop_checkExit10C = verifyCodes checkExit "#!/bin/dash\nexit -1" [2339]+prop_checkExit10D = verifyCodes checkExit "#!/bin/ksh\nexit -1" [2340]+prop_checkExit10E = verifyCodes checkExit "#!/bin/busybox sh\nexit -1" [2339]+-- Return out-of-bounds. They all wrap.+prop_checkExit11A = verifyCodes checkExit "#!/bin/sh\nexit 1000" [3426]+prop_checkExit11B = verifyCodes checkExit "#!/bin/bash\nexit 1000" [2340]+prop_checkExit11C = verifyCodes checkExit "#!/bin/dash\nexit 1000" [2340]+prop_checkExit11D = verifyCodes checkExit "#!/bin/ksh\nexit 1000" [2340]+prop_checkExit11E = verifyCodes checkExit "#!/bin/busybox sh\nexit 1000" [2340]+checkExit = CommandCheck (Exactly "exit") (returnOrExit True) -returnOrExit multi invalid = (f . arguments)- where- f (first:second:_) =- multi (getId first)- f [value] =- when (isInvalid $ literal value) $- invalid (getId value)- f _ = return ()+returnOrExit :: Bool -> Token -> Analysis+returnOrExit isExit cmd =+ case arguments cmd of+ (first:second:_) ->+ if isExit+ then err (getId first) 2241 "The exit status can only be one integer 0-255. Use stdout for other data."+ else err (getId first) 2151 "Only one integer 0-255 can be returned. Use stdout for other data."+ [] -> return ()+ [arg] -> do+ shell <- asks shellType+ let id = getId arg+ let returnRange =+ case shell of+ Sh -> "0-255"+ Bash -> "0-255"+ BusyboxSh -> "0-255"+ Ksh -> "an integer"+ Dash -> "an integer" -- a positive one, at that - isInvalid s = null s || any (not . isDigit) s || length s > 5- || let value = (read s :: Integer) in value > 255+ let (isNegative, isOutOfRange, isNaN) = properties arg+ -- These cases have strong overlap, so order matters.+ case shell of+ _ | isNaN ->+ if isExit+ then err id 2242 "Can only exit with status 0-255. Other data should be written to stdout/stderr."+ else err id 2152 $ "Can only return " ++ returnRange ++ ". Other data should be written to stdout." + Sh | isNegative || isOutOfRange -> err id 3426 "Return/exit values outside 0-255 are undefined in POSIX sh."+ Dash | isNegative -> err id 2339 "Dash does not wrap negative return/exit values. Use a positive integer."+ BusyboxSh | isNegative -> err id 2339 "Busybox does not wrap negative return/exit values. Use a positive integer."++ _ | isExit && isOutOfRange -> warn id 2340 "Exit codes wrap to the range of 0-255. Prefer a canonical exit code."++ Bash | isOutOfRange -> warn id 2341 "Bash wraps return codes to the range 0-255. Prefer a canonical return code."+ BusyboxSh | isOutOfRange -> warn id 2341 "Busybox wraps return codes to the range 0-255. Prefer a canonical return code."++ _ -> return ()+ where+ properties :: Token -> (Bool, Bool, Bool) -- Return whether token (isNegative, isOutOfRange (0-256), isNaN)+ properties t =+ case literal t of+ '-':s | all isDigit s -> (True, True, False)+ s | all isDigit s -> (False, (read s :: Integer) >= 256, False)+ _ -> (False, False, True)+ literal token = runIdentity $ getLiteralStringExt lit token lit (T_DollarBraced {}) = return "0" lit (T_DollarArithmetic {}) = return "0"@@ -469,9 +643,9 @@ termS <- getLiteralString term let cmdS = getLiteralStringDef " " arg - guard $ execS `elem` ["-exec", "-execdir"] && termS `elem` [";", "+"]+ guard $ execS `elem` ["-exec", "-execdir", "-ok", "-okdir"] && termS `elem` [";", "+"] guard $ cmdS `matches` commandRegex- return $ warn (getId exec) 2150 "-exec does not invoke a shell. Rewrite or use -exec sh -c .. ."+ return $ warn (getId exec) 2150 (execS ++ " does not invoke a shell. Rewrite or use " ++ execS ++ " sh -c .. .") check _ = Nothing commandRegex = mkRegex "[ |;]" @@ -504,7 +678,7 @@ prop_checkInjectableFindSh1 = verify checkInjectableFindSh "find . -exec sh -c 'echo {}' \\;" prop_checkInjectableFindSh2 = verify checkInjectableFindSh "find . -execdir bash -c 'rm \"{}\"' ';'"-prop_checkInjectableFindSh3 = verifyNot checkInjectableFindSh "find . -exec sh -c 'rm \"$@\"' _ {} \\;"+prop_checkInjectableFindSh3 = verifyNot checkInjectableFindSh "find . -ok sh -c 'rm \"$@\"' _ {} \\;" checkInjectableFindSh = CommandCheck (Basename "find") (check . arguments) where check args = do@@ -518,7 +692,7 @@ match (p:tests) args pattern = [- (`elem` ["-exec", "-execdir"]),+ (`elem` ["-exec", "-execdir", "-ok", "-okdir"]), (`elem` ["sh", "bash", "dash", "ksh"]), (== "-c") ]@@ -677,10 +851,12 @@ prop_checkPrintfVar20 = verifyNot checkPrintfVar "printf '%d %(%s)T' 42" prop_checkPrintfVar21 = verify checkPrintfVar "printf '%d %(%s)T'" prop_checkPrintfVar22 = verify checkPrintfVar "printf '%s\n%s' foo"+prop_checkPrintfVar23 = verifyNot checkPrintfVar "printf -vTODAY '%(%Y)T'" checkPrintfVar = CommandCheck (Exactly "printf") (f . arguments) where f (doubledash:rest) | getLiteralString doubledash == Just "--" = f rest f (dashv:var:rest) | getLiteralString dashv == Just "-v" = f rest+ f (dashvVar:rest) | Just ('-':'v':_:_) <- getLiteralString dashvVar = f rest f (format:params) = check format params f _ = return () @@ -690,7 +866,7 @@ let formats = getPrintfFormats string let formatCount = length formats let argCount = length more- let pluraliseIfMany word n = if n > 1 then word ++ "s" else word+ let pluraliseIfMany word n = if n == 1 then word else word ++ "s" return $ if | argCount == 0 && formatCount == 0 ->@@ -724,6 +900,9 @@ prop_checkGetPrintfFormats5 = getPrintfFormats "%bPassed: %d, %bFailed: %d%b, Skipped: %d, %bErrored: %d%b\\n" == "bdbdbdbdb" prop_checkGetPrintfFormats6 = getPrintfFormats "%s%s" == "ss" prop_checkGetPrintfFormats7 = getPrintfFormats "%s\n%s" == "ss"+prop_checkGetPrintfFormats8 = getPrintfFormats "%ld" == "d"+prop_checkGetPrintfFormats9 = getPrintfFormats "%lld" == "d"+prop_checkGetPrintfFormats10 = getPrintfFormats "%Q" == "Q" getPrintfFormats = getFormats where -- Get the arguments in the string as a string of type characters,@@ -742,17 +921,17 @@ regexBasedGetFormats rest = case matchRegex re rest of- Just [width, precision, typ, rest, _] ->+ Just [width, precision, len, typ, rest, _] -> (if width == "*" then "*" else "") ++ (if precision == "*" then "*" else "") ++ typ ++ getFormats rest Nothing -> take 1 rest ++ getFormats rest where -- constructed based on specifications in "man printf"- re = mkRegex "#?-?\\+? ?0?(\\*|\\d*)\\.?(\\d*|\\*)([diouxXfFeEgGaAcsbq])((\n|.)*)"- -- \____ _____/\___ ____/ \____ ____/\_________ _________/ \______ /- -- V V V V V- -- flags field width precision format character rest+ re = mkRegex "^#?-?\\+? ?0?(\\*|\\d*)\\.?(\\d*|\\*)(hh|h|l|ll|q|L|j|z|Z|t)?([diouxXfFeEgGaAcsbqQSC])((\n|.)*)"+ -- \____ _____/\___ ____/ \____ ____/\__________ ___________/\___________ ___________/\___ ___/+ -- V V V V V V+ -- flags field width precision length modifier format character rest -- field width and precision can be specified with an '*' instead of a digit, -- in which case printf will accept one more argument for each '*' used @@ -893,6 +1072,13 @@ prop_checkFindWithoutPath6 = verifyNot checkFindWithoutPath "find -D exec ." prop_checkFindWithoutPath7 = verifyNot checkFindWithoutPath "find --help" prop_checkFindWithoutPath8 = verifyNot checkFindWithoutPath "find -Hx . -print"+prop_checkFindWithoutPath9 = verifyNot checkFindWithoutPath "find -files0-from - < file"+prop_checkFindWithoutPath10 = verifyNot checkFindWithoutPath "find -files0-from 'paths list.nul' -print"+prop_checkFindWithoutPath11 = verifyNot checkFindWithoutPath "find -L '-files0-from' \"$paths\" -print"+prop_checkFindWithoutPath12 = verify checkFindWithoutPath "find -L"+prop_checkFindWithoutPath13 = verify checkFindWithoutPath "find -L -files0-from"+prop_checkFindWithoutPath14 = verify checkFindWithoutPath "find -name '-files0-from' -print"+prop_checkFindWithoutPath15 = verify checkFindWithoutPath "find -exec echo -files0-from {} \\;" checkFindWithoutPath = CommandCheck (Basename "find") f where f t@(T_SimpleCommand _ _ (cmd:args)) =@@ -903,9 +1089,11 @@ -- after the path, as well as multiple non-flag arguments that are not the -- path. We assume that all the pre-path flags are single characters from a -- list of GNU and macOS flags.- hasPath (first:rest) =- let flag = getLiteralStringDef "___" first in- not ("-" `isPrefixOf` flag) || isLeadingFlag flag && hasPath rest+ hasPath (first:rest)+ | flag == "-files0-from" = not (null rest)+ | otherwise = not ("-" `isPrefixOf` flag) || isLeadingFlag flag && hasPath rest+ where+ flag = getLiteralStringDef "___" first hasPath [] = False isLeadingFlag flag = length flag <= 2 || all (`elem` leadingFlagChars) flag leadingFlagChars="-EHLPXdfsxO0123456789"@@ -930,7 +1118,7 @@ prop_checkTimedCommand3 = verifyNot checkTimedCommand "#!/bin/sh\ntime sleep 1" checkTimedCommand = CommandCheck (Exactly "time") f where f (T_SimpleCommand _ _ (c:args@(_:_))) =- whenShell [Sh, Dash] $ do+ whenShell [Sh, Dash, BusyboxSh] $ do let cmd = last args -- "time" is parsed with a command as argument when (isPiped cmd) $ warn (getId c) 2176 "'time' is undefined for pipelines. time single stage or bash -c instead."@@ -954,7 +1142,7 @@ prop_checkLocalScope1 = verify checkLocalScope "local foo=3" prop_checkLocalScope2 = verifyNot checkLocalScope "f() { local foo=3; }" checkLocalScope = CommandCheck (Exactly "local") $ \t ->- whenShell [Bash, Dash] $ do -- Ksh allows it, Sh doesn't support local+ whenShell [Bash, Dash, BusyboxSh] $ do -- Ksh allows it, Sh doesn't support local path <- getPathM t unless (any isFunctionLike path) $ err (getId $ getCommandTokenOrThis t) 2168 "'local' is only valid in functions."@@ -1005,8 +1193,8 @@ sequence_ $ do options <- getLiteralString arg1 getoptsVar <- getLiteralString name- (T_WhileExpression _ _ body) <- findFirst whileLoop path- caseCmd@(T_CaseExpression _ var _) <- mapMaybe findCase body !!! 0+ (T_WhileExpression _ _ body) <- findFirst whileLoop (NE.toList path)+ T_CaseExpression id var list <- mapMaybe findCase body !!! 0 -- Make sure getopts name and case variable matches [T_DollarBraced _ _ bracedWord] <- return $ getWordParts var@@ -1016,11 +1204,11 @@ -- Make sure the variable isn't modified guard . not $ modifiesVariable params (T_BraceGroup (Id 0) body) getoptsVar - return $ check (getId arg1) (map (:[]) $ filter (/= ':') options) caseCmd+ return $ check (getId arg1) (map (:[]) $ filter (/= ':') options) id list f _ = return () - check :: Id -> [String] -> Token -> Analysis- check optId opts (T_CaseExpression id _ list) = do+ check :: Id -> [String] -> Id -> [(CaseType, [Token], [Token])] -> Analysis+ check optId opts id list = do unless (Nothing `M.member` handledMap) $ do mapM_ (warnUnhandled optId id) $ catMaybes $ M.keys notHandled @@ -1082,32 +1270,76 @@ prop_checkCatastrophicRm11 = verify checkCatastrophicRm "rm -r /{bin,sbin}/$exec" prop_checkCatastrophicRm12 = verify checkCatastrophicRm "rm -r /{{usr,},{bin,sbin}}/$exec" prop_checkCatastrophicRm13 = verifyNot checkCatastrophicRm "rm -r /{{a,b},{c,d}}/$exec"-prop_checkCatastrophicRmA = verify checkCatastrophicRm "rm -rf /usr /lib/nvidia-current/xorg/xorg"-prop_checkCatastrophicRmB = verify checkCatastrophicRm "rm -rf \"$STEAMROOT/\"*"-checkCatastrophicRm = CommandCheck (Basename "rm") $ \t ->- when (isRecursive t) $- mapM_ (mapM_ checkWord . braceExpand) $ arguments t+prop_checkCatastrophicRm13A= verify checkCatastrophicRm "rm -rf /usr /lib/nvidia-current/xorg/xorg"+prop_checkCatastrophicRm13B= verify checkCatastrophicRm "rm -rf \"$STEAMROOT/\"*"+prop_checkCatastrophicRm13C= verify checkCatastrophicRm "rm -rf /boot/*"+prop_checkCatastrophicRm14 = verify checkCatastrophicRm "rm -rf /./etc"+prop_checkCatastrophicRm15 = verify checkCatastrophicRm "rm -rf /etc/../etc"+prop_checkCatastrophicRm16 = verifyNot checkCatastrophicRm "rm -rf /usr/local/../etc"+prop_checkCatastrophicRm17 = verify checkCatastrophicRm "rm -rf /etc/.."+prop_checkCatastrophicRm18 = verify checkCatastrophicRm "rm -rf /./etc/*"+prop_checkCatastrophicRm19 = verifyNot checkCatastrophicRm "rm -rf /etc/*/../foo"+prop_checkCatastrophicRm20 = verify checkCatastrophicRm "rm -rf \"$x/../etc\""+prop_checkCatastrophicRm21 = verifyNot checkCatastrophicRm "rm -rf ../etc"+prop_checkCatastrophicRm22 = verifyNot checkCatastrophicRm "rm -rf foo/../etc"+prop_checkCatastrophicRm23 = verify checkCatastrophicRm "rm -rf /etc/./"+prop_checkCatastrophicRm24 = verify checkCatastrophicRm "rm -rf /*/../etc/"+prop_checkCatastrophicRm25 = verifyNot checkCatastrophicRm "rm -rf /etc/*/../etc"+prop_checkCatastrophicRm26 = verifyNot checkCatastrophicRm "rm -rf /usr/*/../local/etc"+prop_checkCatastrophicRm27 = verify checkCatastrophicRm "rm /bin/*"+prop_checkCatastrophicRm28 = verifyNot checkCatastrophicRm "rm /bin"+prop_checkCatastrophicRm29 = verifyNot checkCatastrophicRm "rm '/bin/*'"+prop_checkCatastrophicRm30 = verifyNot checkCatastrophicRm "rm /home/$foo"+prop_checkCatastrophicRm31 = verify checkCatastrophicRm "rm /home/*$foo*"+checkCatastrophicRm = CommandCheck (Basename "rm") $ \t -> do+ let recursive = isRecursive t+ mapM_ (mapM_ (checkWord recursive) . braceExpand) $ arguments t where isRecursive = any ((`elem` ["r", "R", "recursive"]) . snd) . getAllFlags - checkWord token =- case getLiteralString token of+ checkWord recursive token =+ when (recursive || isGlob token) $+ case getGlobOrLiteralString token of Just str -> when (fixPath str `elem` importantPaths) $ warn (getId token) 2114 "Warning: deletes a system directory."- Nothing ->- checkWord' token+ Nothing -> checkWord' recursive token - checkWord' token = sequence_ $ do+ checkWord' recursive token = sequence_ $ do filename <- getPotentialPath token let path = fixPath filename- return . when (path `elem` importantPaths) $+ return . when (path `elem` importantPaths && (recursive || isGlob token)) $ warn (getId token) 2115 $ "Use \"${var:?}\" to ensure this never expands to " ++ path ++ " ." fixPath filename = let normalized = skipRepeating '/' . skipRepeating '*' $ filename in- if normalized == "/" then normalized else stripTrailing '/' normalized+ if normalized == "/" then normalized else+ canonicalize $ stripTrailing '/' normalized + -- Lexically resolve "." and ".." components so that e.g. "/./etc",+ -- "/etc/../etc" and "/*/../etc" are recognized. A ".." pops the nearest+ -- previous segment, glob or concrete: "/*" expands to top-level entries+ -- "/name", so "/name/../etc" is exactly "/etc". Only a leading ".." of a+ -- relative path survives, since there is nothing above it to pop.+ canonicalize path =+ case resolve [] $ splitPath path of+ [""] | "/" `isPrefixOf` path -> "/"+ resolved -> intercalate "/" resolved+ where+ splitPath s =+ case break (== '/') s of+ (seg, '/':rest) -> seg : splitPath rest+ (seg, _) -> [seg]+ resolve done [] = reverse done+ resolve done (seg:rest)+ | seg == "." = resolve done rest+ | seg == ".." =+ case done of+ top:d | top /= ".." && top /= "" -> resolve d rest+ "":_ -> resolve done rest+ _ -> resolve (seg:done) rest+ | otherwise = resolve (seg:done) rest+ getPotentialPath = getLiteralStringExt f where f (T_Glob _ str) = return str@@ -1125,8 +1357,10 @@ go a r = a : case r of b:rest | b == c && a == b -> rest; _ -> r paths = [- "", "/bin", "/etc", "/home", "/mnt", "/usr", "/usr/share", "/usr/local",- "/var", "/lib", "/dev", "/media", "/boot", "/lib64", "/usr/bin"+ "", "/bin", "/boot", "/dev", "/etc", "/home", "/lib", "/lib64", "/media",+ "/mnt", "/opt", "/proc", "/root", "/run", "/sbin", "/srv", "/sys", "/usr",+ "/usr/bin", "/usr/include", "/usr/lib", "/usr/libexec", "/usr/lib64",+ "/usr/local", "/usr/sbin", "/usr/share", "/var" ] importantPaths = filter (not . null) $ ["", "/", "/*", "/*/*"] >>= (\x -> map (++x) paths)@@ -1195,14 +1429,14 @@ checkWhich = CommandCheck (Basename "which") $ \t -> info (getId $ getCommandTokenOrThis t) 2230 "'which' is non-standard. Use builtin 'command -v' instead." -prop_checkSudoRedirect1 = verify checkSudoRedirect "sudo echo 3 > /proc/file"-prop_checkSudoRedirect2 = verify checkSudoRedirect "sudo cmd < input"-prop_checkSudoRedirect3 = verify checkSudoRedirect "sudo cmd >> file"-prop_checkSudoRedirect4 = verify checkSudoRedirect "sudo cmd &> file"-prop_checkSudoRedirect5 = verifyNot checkSudoRedirect "sudo cmd 2>&1"-prop_checkSudoRedirect6 = verifyNot checkSudoRedirect "sudo cmd 2> log"-prop_checkSudoRedirect7 = verifyNot checkSudoRedirect "sudo cmd > /dev/null 2>&1"-checkSudoRedirect = CommandCheck (Basename "sudo") f+prop_checkSudoRedirect1 = verify (checkSudoRedirect "sudo") "sudo echo 3 > /proc/file"+prop_checkSudoRedirect2 = verify (checkSudoRedirect "doas") "doas cmd < input"+prop_checkSudoRedirect3 = verify (checkSudoRedirect "run0") "run0 cmd >> file"+prop_checkSudoRedirect4 = verify (checkSudoRedirect "sudo") "sudo cmd &> file"+prop_checkSudoRedirect5 = verifyNot (checkSudoRedirect "sudo") "sudo cmd 2>&1"+prop_checkSudoRedirect6 = verifyNot (checkSudoRedirect "doas") "doas cmd 2> log"+prop_checkSudoRedirect7 = verifyNot (checkSudoRedirect "run0") "run0 cmd > /dev/null 2>&1"+checkSudoRedirect cmd = CommandCheck (Basename cmd) f where f t = do t_redir <- getClosestCommandM t@@ -1214,34 +1448,33 @@ case op of T_Less _ -> info (getId op) 2024- "sudo doesn't affect redirects. Use sudo cat file | .."+ "sudo/doas/run0 doesn't affect redirects. Use sudo cat file | .." T_Greater _ -> warn (getId op) 2024- "sudo doesn't affect redirects. Use ..| sudo tee file"+ "sudo/doas/run0 doesn't affect redirects. Use ..| sudo tee file" T_DGREAT _ -> warn (getId op) 2024- "sudo doesn't affect redirects. Use .. | sudo tee -a file"+ "sudo/doas/run0 doesn't affect redirects. Use .. | sudo tee -a file" _ -> return () warnAbout _ = return () special file = concat (oversimplify file) == "/dev/null" -prop_checkSudoArgs1 = verify checkSudoArgs "sudo cd /root"-prop_checkSudoArgs2 = verify checkSudoArgs "sudo export x=3"-prop_checkSudoArgs3 = verifyNot checkSudoArgs "sudo ls /usr/local/protected"-prop_checkSudoArgs4 = verifyNot checkSudoArgs "sudo ls && export x=3"-prop_checkSudoArgs5 = verifyNot checkSudoArgs "sudo echo ls"-prop_checkSudoArgs6 = verifyNot checkSudoArgs "sudo -n -u export ls"-prop_checkSudoArgs7 = verifyNot checkSudoArgs "sudo docker export foo"-checkSudoArgs = CommandCheck (Basename "sudo") f+prop_checkSudoArgs1 = verify (checkSudoArgs "sudo") "sudo cd /root"+prop_checkSudoArgs2 = verify (checkSudoArgs "run0") "run0 export x=3"+prop_checkSudoArgs3 = verifyNot (checkSudoArgs "sudo") "sudo ls /usr/local/protected"+prop_checkSudoArgs4 = verifyNot (checkSudoArgs "doas") "doas ls && export x=3"+prop_checkSudoArgs5 = verifyNot (checkSudoArgs "sudo") "sudo echo ls"+prop_checkSudoArgs6 = verifyNot (checkSudoArgs "sudo") "sudo -n -u export ls"+prop_checkSudoArgs7 = verifyNot (checkSudoArgs "sudo") "sudo docker export foo"+checkSudoArgs cmd = CommandCheck (Basename cmd) f where f t = sequence_ $ do opts <- parseOpts $ arguments t- let nonFlags = [x | ("",(x, _)) <- opts]- commandArg <- nonFlags !!! 0+ (_,(commandArg, _)) <- find (null . fst) opts command <- getLiteralString commandArg guard $ command `elem` builtins- return $ warn (getId t) 2232 $ "Can't use sudo with builtins like " ++ command ++ ". Did you want sudo sh -c .. instead?"- builtins = [ "cd", "eval", "export", "history", "read", "source", "wait" ]+ return $ warn (getId t) 2232 $ "Can't use sudo/doas/run0 with builtins like " ++ command ++ ". Did you want sudo/doas/run0 sh -c .. instead?"+ builtins = [ "cd", "command", "declare", "eval", "exec", "exit", "export", "hash", "history", "local", "popd", "pushd", "read", "readonly", "return", "set", "source", "trap", "type", "typeset", "ulimit", "umask", "unset", "wait" ] -- This mess is why ShellCheck prefers not to know. parseOpts = getBsdOpts "vAknSbEHPa:g:h:p:u:c:T:r:" @@ -1430,26 +1663,27 @@ prop_checkBackreferencingDeclaration7 = verify (checkBackreferencingDeclaration "declare") "declare x=var $k=$x" checkBackreferencingDeclaration cmd = CommandCheck (Exactly cmd) check where- check t = foldM_ perArg M.empty $ arguments t+ check t = do+ maybeCfga <- asks cfgAnalysis+ mapM_ (\cfga -> foldM_ (perArg cfga) M.empty $ arguments t) maybeCfga - perArg leftArgs t =+ perArg cfga leftArgs t = case t of T_Assignment id _ name idx t -> do- warnIfBackreferencing leftArgs $ t:idx+ warnIfBackreferencing cfga leftArgs $ t:idx return $ M.insert name id leftArgs t -> do- warnIfBackreferencing leftArgs [t]+ warnIfBackreferencing cfga leftArgs [t] return leftArgs - warnIfBackreferencing backrefs l = do- references <- findReferences l+ warnIfBackreferencing cfga backrefs l = do+ references <- findReferences cfga l let reused = M.intersection backrefs references mapM msg $ M.toList reused msg (name, id) = warn id 2318 $ "This assignment is used again in this '" ++ cmd ++ "', but won't have taken effect. Use two '" ++ cmd ++ "'s." - findReferences list = do- cfga <- asks cfgAnalysis+ findReferences cfga list = do let graph = CF.graph cfga let nodesMap = CF.tokenToNodes cfga let nodes = S.unions $ map (\id -> M.findWithDefault S.empty id nodesMap) $ map getId $ list
src/ShellCheck/Checks/ControlFlow.hs view
@@ -78,7 +78,7 @@ runNodeChecks :: [ControlFlowNodeCheck] -> ControlFlowCheck runNodeChecks perNode = do cfg <- asks cfgAnalysis- runOnAll cfg+ mapM_ runOnAll cfg where getData datas n@(node, label) = do (pre, post) <- M.lookup node datas
src/ShellCheck/Checks/Custom.hs view
@@ -1,7 +1,7 @@ {- This empty file is provided for ease of patching in site specific checks. However, there are no guarantees regarding compatibility between versions.--} +-} {-# LANGUAGE TemplateHaskell #-} module ShellCheck.Checks.Custom (checker, ShellCheck.Checks.Custom.runTests) where
src/ShellCheck/Checks/ShellSupport.hs view
@@ -19,6 +19,7 @@ -} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE ViewPatterns #-} module ShellCheck.Checks.ShellSupport (checker , ShellCheck.Checks.ShellSupport.runTests) where import ShellCheck.AST@@ -60,6 +61,9 @@ ,checkBraceExpansionVars ,checkMultiDimensionalArrays ,checkPS1Assignments+ ,checkMultipleBangs+ ,checkBangAfterPipe+ ,checkNegatedUnaryOps ] testChecker (ForShell _ t) =@@ -73,22 +77,24 @@ prop_checkForDecimals1 = verify checkForDecimals "((3.14*c))" prop_checkForDecimals2 = verify checkForDecimals "foo[1.2]=bar" prop_checkForDecimals3 = verifyNot checkForDecimals "declare -A foo; foo[1.2]=bar"-checkForDecimals = ForShell [Sh, Dash, Bash] f+checkForDecimals = ForShell [Sh, Dash, BusyboxSh, Bash] f where f t@(TA_Expansion id _) = sequence_ $ do- str <- getLiteralString t- first <- str !!! 0- guard $ isDigit first && '.' `elem` str+ first:rest <- getLiteralString t+ guard $ isDigit first && '.' `elem` rest return $ err id 2079 "(( )) doesn't support decimals. Use bc or awk." f _ = return () prop_checkBashisms = verify checkBashisms "while read a; do :; done < <(a)"-prop_checkBashisms2 = verify checkBashisms "[ foo -nt bar ]"+prop_checkBashisms2 = verifyNot checkBashisms "[ foo -nt bar ]" prop_checkBashisms3 = verify checkBashisms "echo $((i++))" prop_checkBashisms4 = verify checkBashisms "rm !(*.hs)" prop_checkBashisms5 = verify checkBashisms "source file" prop_checkBashisms6 = verify checkBashisms "[ \"$a\" == 42 ]"+prop_checkBashisms6b = verify checkBashisms "test \"$a\" == 42"+prop_checkBashisms6c = verify checkBashisms "[ foo =~ bar ]"+prop_checkBashisms6d = verify checkBashisms "test foo =~ bar" prop_checkBashisms7 = verify checkBashisms "echo ${var[1]}" prop_checkBashisms8 = verify checkBashisms "echo ${!var[@]}" prop_checkBashisms9 = verify checkBashisms "echo ${!var*}"@@ -104,6 +110,7 @@ prop_checkBashisms19 = verify checkBashisms "foo > file*.txt" prop_checkBashisms20 = verify checkBashisms "read -ra foo" prop_checkBashisms21 = verify checkBashisms "[ -a foo ]"+prop_checkBashisms21b = verify checkBashisms "test -a foo" prop_checkBashisms22 = verifyNot checkBashisms "[ foo -a bar ]" prop_checkBashisms23 = verify checkBashisms "trap mything ERR INT" prop_checkBashisms24 = verifyNot checkBashisms "trap mything INT TERM"@@ -141,8 +148,8 @@ prop_checkBashisms54 = verify checkBashisms "#!/bin/sh\nfoo+=bar" prop_checkBashisms55 = verify checkBashisms "#!/bin/sh\necho ${@%foo}" prop_checkBashisms56 = verifyNot checkBashisms "#!/bin/sh\necho ${##}"-prop_checkBashisms57 = verifyNot checkBashisms "#!/bin/dash\nulimit -c 0"-prop_checkBashisms58 = verify checkBashisms "#!/bin/sh\nulimit -c 0"+prop_checkBashisms57 = verifyNot checkBashisms "#!/bin/dash\nulimit -m unlimited"+prop_checkBashisms58 = verify checkBashisms "#!/bin/sh\nulimit -x unlimited" prop_checkBashisms59 = verify checkBashisms "#!/bin/sh\njobs -s" prop_checkBashisms60 = verifyNot checkBashisms "#!/bin/sh\njobs -p" prop_checkBashisms61 = verifyNot checkBashisms "#!/bin/sh\njobs -lp"@@ -168,7 +175,7 @@ prop_checkBashisms81 = verifyNot checkBashisms "#!/bin/dash\nhash -v" prop_checkBashisms82 = verifyNot checkBashisms "#!/bin/sh\nset -v +o allexport -o errexit -C" prop_checkBashisms83 = verifyNot checkBashisms "#!/bin/sh\nset --"-prop_checkBashisms84 = verify checkBashisms "#!/bin/sh\nset -o pipefail"+prop_checkBashisms84 = verifyNot checkBashisms "#!/bin/sh\nset -o pipefail" prop_checkBashisms85 = verify checkBashisms "#!/bin/sh\nset -B" prop_checkBashisms86 = verifyNot checkBashisms "#!/bin/dash\nset -o emacs" prop_checkBashisms87 = verify checkBashisms "#!/bin/sh\nset -o emacs"@@ -184,49 +191,103 @@ prop_checkBashisms97 = verify checkBashisms "#!/bin/sh\necho ${var,}" prop_checkBashisms98 = verify checkBashisms "#!/bin/sh\necho ${var^^}" prop_checkBashisms99 = verify checkBashisms "#!/bin/dash\necho [^f]oo"-checkBashisms = ForShell [Sh, Dash] $ \t -> do+prop_checkBashisms100 = verify checkBashisms "read -r"+prop_checkBashisms101 = verify checkBashisms "read"+prop_checkBashisms102 = verifyNot checkBashisms "read -r foo"+prop_checkBashisms103 = verifyNot checkBashisms "read foo"+prop_checkBashisms104 = verifyNot checkBashisms "read ''"+prop_checkBashisms105 = verifyNot checkBashisms "#!/bin/busybox sh\nset -o pipefail"+prop_checkBashisms106 = verifyNot checkBashisms "#!/bin/busybox sh\nx=x\n[[ \"$x\" = \"$x\" ]]"+prop_checkBashisms107 = verifyNot checkBashisms "#!/bin/busybox sh\nx=x\n[ \"$x\" == \"$x\" ]"+prop_checkBashisms108 = verifyNot checkBashisms "#!/bin/busybox sh\necho magic &> /dev/null"+prop_checkBashisms109 = verifyNot checkBashisms "#!/bin/busybox sh\ntrap stop EXIT SIGTERM"+prop_checkBashisms110 = verifyNot checkBashisms "#!/bin/busybox sh\nsource /dev/null"+prop_checkBashisms111 = verify checkBashisms "#!/bin/dash\nx='test'\n${x:0:3}" -- SC3057+prop_checkBashisms112 = verifyNot checkBashisms "#!/bin/busybox sh\nx='test'\n${x:0:3}" -- SC3057+prop_checkBashisms113 = verify checkBashisms "#!/bin/dash\nx='test'\n${x/st/xt}" -- SC3060+prop_checkBashisms114 = verifyNot checkBashisms "#!/bin/busybox sh\nx='test'\n${x/st/xt}" -- SC3060+prop_checkBashisms115 = verify checkBashisms "#!/bin/busybox sh\nx='test'\n${!x}" -- SC3053+prop_checkBashisms116 = verify checkBashisms "#!/bin/busybox sh\nx='test'\n${x[1]}" -- SC3054+prop_checkBashisms117 = verify checkBashisms "#!/bin/busybox sh\nx='test'\n${!x[@]}" -- SC3055+prop_checkBashisms118 = verify checkBashisms "#!/bin/busybox sh\nxyz=1\n${!x*}" -- SC3056+prop_checkBashisms119 = verify checkBashisms "#!/bin/busybox sh\nx='test'\n${x^^[t]}" -- SC3059+prop_checkBashisms120 = verify checkBashisms "#!/bin/sh\n[ x == y ]"+prop_checkBashisms121 = verifyNot checkBashisms "#!/bin/sh\n# shellcheck shell=busybox\n[ x == y ]"+prop_checkBashisms122 = verifyNot checkBashisms "#!/bin/dash\n$'a'"+prop_checkBashisms123 = verifyNot checkBashisms "#!/bin/busybox sh\n$'a'"+prop_checkBashisms124 = verify checkBashisms "#!/bin/dash\ntype -p test"+prop_checkBashisms125 = verifyNot checkBashisms "#!/bin/busybox sh\ntype -p test"+prop_checkBashisms126 = verifyNot checkBashisms "#!/bin/busybox sh\nread -p foo -r bar"+prop_checkBashisms127 = verifyNot checkBashisms "#!/bin/busybox sh\necho -ne foo"+prop_checkBashisms128 = verify checkBashisms "#!/bin/dash\ntype -p test"+prop_checkBashisms129 = verify checkBashisms "#!/bin/sh\n[ -k /tmp ]"+prop_checkBashisms130 = verifyNot checkBashisms "#!/bin/dash\ntest -k /tmp"+prop_checkBashisms131 = verify checkBashisms "#!/bin/sh\n[ -o errexit ]"+prop_checkBashisms132 = verify checkBashisms "echo $\"hello\"" -- SC3004+prop_checkBashisms133 = verify checkBashisms "for ((;;)); do break; done" -- SC3005+prop_checkBashisms134 = verify checkBashisms "((var))" -- SC3006+prop_checkBashisms135 = verify checkBashisms "var=$[1 + 2]" -- SC3007+prop_checkBashisms136 = verify checkBashisms "select x; do :; done" -- SC3008+prop_checkBashisms137a = verify checkBashisms "echo {a,b}" -- SC3009+prop_checkBashisms137b = verify checkBashisms "echo {1..3}" -- SC3009+prop_checkBashisms138 = verify checkBashisms "[[ -z $var ]]" -- SC3010+prop_checkBashisms139 = verify checkBashisms "cat <<< foo" -- SC3011+prop_checkBashisms140a = verify checkBashisms "[ a '<' b ]" -- SC3012+prop_checkBashisms140b = verify checkBashisms "test a \\> b" -- SC3012+prop_checkBashisms141 = verify checkBashisms "echo $((2 ** 3))" -- SC3019+prop_checkBashisms142 = verify checkBashisms "make |& less" -- SC3029+prop_checkBashisms143 = verify checkBashisms "a=(foo bar)" -- SC3030+prop_checkBashisms144 = verify checkBashisms "coproc foo { :; }" -- SC3032+prop_checkBashisms145a = verify checkBashisms "#!/bin/sh\nf() { local i=; }" -- SC3043+prop_checkBashisms145b = verifyNot checkBashisms "#!/bin/dash\nf() { local i=; }" -- SC3043+prop_checkBashisms146 = verify checkBashisms "readarray < file" -- SC3044+prop_checkBashisms147 = verify checkBashisms "[ -R ref ]" -- SC3063+prop_checkBashisms148 = verify checkBashisms "[ -N file ]" -- SC3064+prop_checkBashisms149 = verify checkBashisms "[ -G file ]" -- SC3066+prop_checkBashisms150 = verify checkBashisms "[ -O file ]" -- SC3067+prop_checkBashisms151 = verifyNot checkBashisms "#!/bin/busybox sh\npwd | tee >(gzip > log.gz)" -- SC3001+checkBashisms = ForShell [Sh, Dash, BusyboxSh] $ \t -> do params <- ask kludge params t where -- This code was copy-pasted from Analytics where params was a variable kludge params = bashism where- isDash = shellType params == Dash+ isBusyboxSh = shellType params == BusyboxSh+ isDash = shellType params == Dash || isBusyboxSh warnMsg id code s = if isDash then err id code $ "In dash, " ++ s ++ " not supported." else warn id code $ "In POSIX sh, " ++ s ++ " undefined."+ asStr = getLiteralString - bashism (T_ProcSub id _ _) = warnMsg id 3001 "process substitution is"+ bashism (T_ProcSub id _ _) = unless isBusyboxSh $ warnMsg id 3001 "process substitution is" bashism (T_Extglob id _ _) = warnMsg id 3002 "extglob is"- bashism (T_DollarSingleQuoted id _) = warnMsg id 3003 "$'..' is" bashism (T_DollarDoubleQuoted id _) = warnMsg id 3004 "$\"..\" is" bashism (T_ForArithmetic id _ _ _ _) = warnMsg id 3005 "arithmetic for loops are" bashism (T_Arithmetic id _) = warnMsg id 3006 "standalone ((..)) is" bashism (T_DollarBracket id _) = warnMsg id 3007 "$[..] in place of $((..)) is" bashism (T_SelectIn id _ _ _) = warnMsg id 3008 "select loops are" bashism (T_BraceExpansion id _) = warnMsg id 3009 "brace expansion is"- bashism (T_Condition id DoubleBracket _) = warnMsg id 3010 "[[ ]] is"+ bashism (T_Condition id DoubleBracket _ _) =+ unless isBusyboxSh $ warnMsg id 3010 "[[ ]] is" bashism (T_HereString id _) = warnMsg id 3011 "here-strings are"- bashism (TC_Binary id SingleBracket op _ _)- | op `elem` [ "<", ">", "\\<", "\\>", "<=", ">=", "\\<=", "\\>="] =- unless isDash $ warnMsg id 3012 $ "lexicographical " ++ op ++ " is"- bashism (TC_Binary id SingleBracket op _ _)- | op `elem` [ "-ot", "-nt", "-ef" ] =- unless isDash $ warnMsg id 3013 $ op ++ " is"- bashism (TC_Binary id SingleBracket "==" _ _) =- warnMsg id 3014 "== in place of = is"- bashism (TC_Binary id SingleBracket "=~" _ _) =- warnMsg id 3015 "=~ regex matching is"- bashism (TC_Unary id SingleBracket "-v" _) =- warnMsg id 3016 "unary -v (in place of [ -n \"${var+x}\" ]) is"- bashism (TC_Unary id _ "-a" _) =- warnMsg id 3017 "unary -a in place of -e is"++ bashism (TC_Binary id _ op _ _) =+ checkTestOp bashismBinaryTestFlags op id+ bashism (T_SimpleCommand id _ [asStr -> Just "test", lhs, asStr -> Just op, rhs]) =+ checkTestOp bashismBinaryTestFlags op id+ bashism (TC_Unary id _ op _) =+ checkTestOp bashismUnaryTestFlags op id+ bashism (T_SimpleCommand id _ [asStr -> Just "test", asStr -> Just op, _]) =+ checkTestOp bashismUnaryTestFlags op id+ bashism (TA_Unary id op _) | op `elem` [ "|++", "|--", "++|", "--|"] = warnMsg id 3018 $ filter (/= '|') op ++ " is" bashism (TA_Binary id "**" _ _) = warnMsg id 3019 "exponentials are"- bashism (T_FdRedirect id "&" (T_IoFile _ (T_Greater _) _)) = warnMsg id 3020 "&> is"+ bashism (T_FdRedirect id "&" (T_IoFile _ (T_Greater _) _)) =+ unless isBusyboxSh $ warnMsg id 3020 "&> is" bashism (T_FdRedirect id "" (T_IoFile _ (T_GREATAND _) file)) = unless (all isDigit $ onlyLiteralString file) $ warnMsg id 3021 ">& filename (as opposed to >& fd) is" bashism (T_FdRedirect id ('{':_) _) = warnMsg id 3022 "named file descriptors are"@@ -246,7 +307,8 @@ warnMsg id 3028 $ str ++ " is" bashism t@(T_DollarBraced id _ token) = do- mapM_ check expansion+ unless isBusyboxSh $ mapM_ check simpleExpansions+ mapM_ check advancedExpansions when (isBashVariable var) $ warnMsg id 3028 $ var ++ " is" where@@ -274,8 +336,12 @@ bashism t@(T_SimpleCommand _ _ (cmd:arg:_)) | t `isCommand` "echo" && argString `matches` flagRegex =- if isDash+ if isBusyboxSh then+ unless (argString `matches` busyboxFlagRegex) $+ warnMsg (getId arg) 3036 "echo flags besides -n and -e"+ else if isDash+ then when (argString /= "-n") $ warnMsg (getId arg) 3036 "echo flags besides -n" else@@ -283,6 +349,7 @@ where argString = concat $ oversimplify arg flagRegex = mkRegex "^-[eEsn]+$"+ busyboxFlagRegex = mkRegex "^-[en]+$" bashism t@(T_SimpleCommand _ _ (cmd:arg:_)) | getLiteralString cmd == Just "exec" && "-" `isPrefixOf` concat (oversimplify arg) =@@ -317,7 +384,7 @@ checkFlags (flag@(fid, flag'):rest) | startsOption flag' = do unless (flag' `matches` validFlagsRegex) $- forM_ (tail flag') $ \letter ->+ forM_ (drop 1 flag') $ \letter -> when (letter `notElem` optionsSet) $ warnMsg fid 3041 $ "set flag " <> ('-':letter:" is") checkOptions rest@@ -337,8 +404,8 @@ beginsWithDoubleDash = (`matches` mkRegex "^--.+$") longOptions = Set.fromList [ "allexport", "errexit", "ignoreeof", "monitor", "noclobber"- , "noexec", "noglob", "nolog", "notify" , "nounset", "verbose"- , "vi", "xtrace" ]+ , "noexec", "noglob", "nolog", "notify" , "nounset", "pipefail"+ , "verbose", "vi", "xtrace" ] bashism t@(T_SimpleCommand id _ (cmd:rest)) = let name = fromMaybe "" $ getCommandName t@@ -356,7 +423,8 @@ (\x -> (not . null . snd $ x) && snd x `notElem` allowed) flags return . warnMsg (getId word) 3045 $ name ++ " -" ++ flag ++ " is" - when (name == "source") $ warnMsg id 3046 "'source' in place of '.' is"+ when (name == "source" && not isBusyboxSh) $+ warnMsg id 3046 "'source' in place of '.' is" when (name == "trap") $ let check token = sequence_ $ do@@ -365,7 +433,7 @@ return $ do when (upper `elem` ["ERR", "DEBUG", "RETURN"]) $ warnMsg (getId token) 3047 $ "trapping " ++ str ++ " is"- when ("SIG" `isPrefixOf` upper) $+ when (not isBusyboxSh && "SIG" `isPrefixOf` upper) $ warnMsg (getId token) 3048 "prefixing signal names with 'SIG' is" when (not isDash && upper /= str) $@@ -379,6 +447,9 @@ let literal = onlyLiteralString format guard $ "%q" `isInfixOf` literal return $ warnMsg (getId format) 3050 "printf %q is"++ when (name == "read" && all isFlag rest) $+ warnMsg (getId cmd) 3061 "read without a variable is" where unsupportedCommands = [ "let", "caller", "builtin", "complete", "compgen", "declare", "dirs", "disown",@@ -392,17 +463,24 @@ ("hash", Just $ if isDash then ["r", "v"] else ["r"]), ("jobs", Just ["l", "p"]), ("printf", Just []),- ("read", Just $ if isDash then ["r", "p"] else ["r"]),+ ("read", Just $ if isDash || isBusyboxSh then ["r", "p"] else ["r"]), ("readonly", Just ["p"]), ("trap", Just []),- ("type", Just []),- ("ulimit", if isDash then Nothing else Just ["f"]),+ ("type", Just $ if isBusyboxSh then ["p"] else []),+ ("ulimit",+ Just $+ if isDash+ then ["H", "S", "a", "c", "d", "f", "l", "m", "n", "p", "r", "s", "t", "v", "w"]+ else ["H", "S", "a", "c", "d", "f", "n", "s", "t", "v"] -- POSIX.1-2024+ ), ("umask", Just ["S"]), ("unset", Just ["f", "v"]), ("wait", Just []) ] bashism t@(T_SourceCommand id src _)- | getCommandName src == Just "source" = warnMsg id 3051 "'source' in place of '.' is"+ | getCommandName src == Just "source" =+ unless isBusyboxSh $+ warnMsg id 3051 "'source' in place of '.' is" bashism (TA_Expansion _ (T_Literal id str : _)) | str `matches` radix = warnMsg id 3052 "arithmetic base conversion is" where@@ -410,14 +488,16 @@ bashism _ = return () varChars="_0-9a-zA-Z"- expansion = let re = mkRegex in [+ advancedExpansions = let re = mkRegex in [ (re $ "^![" ++ varChars ++ "]", 3053, "indirect expansion is"), (re $ "^[" ++ varChars ++ "]+\\[.*\\]$", 3054, "array references are"), (re $ "^![" ++ varChars ++ "]+\\[[*@]]$", 3055, "array key expansion is"), (re $ "^![" ++ varChars ++ "]+[*@]$", 3056, "name matching prefixes are"),+ (re $ "^[" ++ varChars ++ "*@]+(\\[.*\\])?[,^]", 3059, "case modification is")+ ]+ simpleExpansions = let re = mkRegex in [ (re $ "^[" ++ varChars ++ "*@]+:[^-=?+]", 3057, "string indexing is"), (re $ "^([*@][%#]|#[@*])", 3058, "string operations on $@/$* are"),- (re $ "^[" ++ varChars ++ "*@]+(\\[.*\\])?[,^]", 3059, "case modification is"), (re $ "^[" ++ varChars ++ "*@]+(\\[.*\\])?/", 3060, "string replacement is") ] bashVars = [@@ -425,13 +505,18 @@ -- for shell identification. "OSTYPE", "MACHTYPE", "HOSTTYPE", "HOSTNAME", "DIRSTACK", "EUID", "UID", "SHLVL", "PIPESTATUS", "SHELLOPTS",- "_", "BASHOPTS", "BASHPID", "BASH_ALIASES", "BASH_ARGC",+ "_", "BASH", "BASHOPTS", "BASHPID", "BASH_ALIASES", "BASH_ARGC", "BASH_ARGV", "BASH_ARGV0", "BASH_CMDS", "BASH_COMMAND",- "BASH_EXECUTION_STRING", "BASH_LINENO", "BASH_REMATCH", "BASH_SOURCE",- "BASH_SUBSHELL", "BASH_VERSINFO", "EPOCHREALTIME", "EPOCHSECONDS",- "FUNCNAME", "GROUPS", "MACHTYPE", "MAPFILE"+ "BASH_EXECUTION_STRING", "BASH_LINENO", "BASH_LOADABLES_PATH",+ "BASH_REMATCH", "BASH_SOURCE", "BASH_SUBSHELL", "BASH_VERSINFO",+ "COMP_CWORD", "COMP_KEY", "COMP_LINE", "COMP_POINT", "COMP_TYPE",+ "COMP_WORDBREAKS", "COMP_WORDS", "COPROC", "FUNCNAME", "GROUPS",+ "HISTCMD", "MAPFILE" ]- bashDynamicVars = [ "RANDOM", "SECONDS" ]+ bashDynamicVars = [+ "BASH_MONOSECONDS", "EPOCHREALTIME", "EPOCHSECONDS", "RANDOM",+ "SECONDS", "SRANDOM"+ ] dashVars = [ "_" ] isBashVariable var = (var `elem` bashDynamicVars@@ -443,6 +528,50 @@ Assignment (_, _, name, _) -> name == var _ -> False + checkTestOp table op id = sequence_ $ do+ (code, shells, msg) <- Map.lookup op table+ guard . not $ shellType params `elem` shells+ return $ warnMsg id code (msg op)+++buildTestFlagMap list = Map.fromList $ concatMap (\(x,y) -> map (\c -> (c,y)) x) list+bashismBinaryTestFlags = buildTestFlagMap [+ -- ([list of applicable flags],+ -- (error code, exempt shells, message builder :: String -> String)),+ --+ -- Distinct error codes allow the wiki to give more helpful, targeted+ -- information.+ (["<", ">", "\\<", "\\>", "<=", ">=", "\\<=", "\\>="],+ (3012, [Dash, BusyboxSh], \op -> "lexicographical " ++ op ++ " is")),+ (["=="],+ (3014, [BusyboxSh], \op -> op ++ " in place of = is")),+ (["=~"],+ (3015, [], \op -> op ++ " regex matching is")),++ ([], (0,[],const ""))+ ]+bashismUnaryTestFlags = buildTestFlagMap [+ (["-v"],+ (3016, [], \op -> "test " ++ op ++ " (in place of [ -n \"${var+x}\" ]) is")),+ (["-a"],+ (3017, [], \op -> "unary " ++ op ++ " in place of -e is")),+ (["-o"],+ (3062, [], \op -> "test " ++ op ++ " to check options is")),+ (["-R"],+ (3063, [], \op -> "test " ++ op ++ " and namerefs in general are")),+ (["-N"],+ (3064, [], \op -> "test " ++ op ++ " is")),+ (["-k"],+ (3065, [Dash, BusyboxSh], \op -> "test " ++ op ++ " is")),+ (["-G"],+ (3066, [Dash, BusyboxSh], \op -> "test " ++ op ++ " is")),+ (["-O"],+ (3067, [Dash, BusyboxSh], \op -> "test " ++ op ++ " is")),++ ([], (0,[],const ""))+ ]++ prop_checkEchoSed1 = verify checkEchoSed "FOO=$(echo \"$cow\" | sed 's/foo/bar/g')" prop_checkEchoSed1b = verify checkEchoSed "FOO=$(sed 's/foo/bar/g' <<< \"$cow\")" prop_checkEchoSed2 = verify checkEchoSed "rm $(echo $cow | sed -e 's,foo,bar,')"@@ -557,6 +686,47 @@ enclosedRegex = mkRegex "\\\\\\[.*\\\\\\]" -- FIXME: shouldn't be eager escapeRegex = mkRegex "\\\\x1[Bb]|\\\\e|\x1B|\\\\033" ++prop_checkMultipleBangs1 = verify checkMultipleBangs "! ! true"+prop_checkMultipleBangs2 = verifyNot checkMultipleBangs "! true"+checkMultipleBangs = ForShell [Dash, BusyboxSh, Sh] f+ where+ f token = case token of+ T_Banged id (T_Banged _ _) ->+ err id 2325 "Multiple ! in front of pipelines are a bash/ksh extension. Use only 0 or 1."+ _ -> return ()+++prop_checkBangAfterPipe1 = verify checkBangAfterPipe "true | ! true"+prop_checkBangAfterPipe2 = verifyNot checkBangAfterPipe "true | ( ! true )"+prop_checkBangAfterPipe3 = verifyNot checkBangAfterPipe "! ! true | true"+checkBangAfterPipe = ForShell [Dash, BusyboxSh, Sh, Bash] f+ where+ f token = case token of+ T_Pipeline _ _ cmds -> mapM_ check cmds+ _ -> return ()++ check token = case token of+ T_Banged id _ ->+ err id 2326 "! is not allowed in the middle of pipelines. Use command group as in cmd | { ! cmd; } if necessary."+ _ -> return ()+++prop_checkNegatedUnaryOps1 = verify checkNegatedUnaryOps "[ ! -o braceexpand ]"+prop_checkNegatedUnaryOps2 = verifyNot checkNegatedUnaryOps "[ -o braceexpand ]"+prop_checkNegatedUnaryOps3 = verifyNot checkNegatedUnaryOps "[[ ! -o braceexpand ]]"+prop_checkNegatedUnaryOps4 = verifyNot checkNegatedUnaryOps "! [ -o braceexpand ]"+prop_checkNegatedUnaryOps5 = verify checkNegatedUnaryOps "[ ! -a file ]"+checkNegatedUnaryOps = ForShell [Bash] f+ where+ f token = case token of+ TC_Unary id SingleBracket "!" (TC_Unary _ _ op _) | op `elem` ["-a", "-o"] ->+ err id 2332 $ msg op+ _ -> return ()++ msg "-o" = "[ ! -o opt ] is always true because -o becomes logical OR. Use [[ ]] or ! [ -o opt ]."+ msg "-a" = "[ ! -a file ] is always true because -a becomes logical AND. Use -e instead."+ msg _ = pleaseReport "unhandled negated unary message" return [] runTests = $( [| $(forAllProperties) (quickCheckWithResult (stdArgs { maxSuccess = 1 }) ) |])
src/ShellCheck/Data.hs view
@@ -1,6 +1,10 @@ module ShellCheck.Data where +import ShellCheck.AST (Annotation(ShellOverride)) import ShellCheck.Interface+import ShellCheck.Prelude (headOrDefault)+import Data.List (isSuffixOf)+import Data.Maybe (listToMaybe) import Data.Version (showVersion) @@ -28,6 +32,12 @@ -- Generic "", "_", "rest", "REST", + -- POSIX+ "CDPATH", "ENV", "FCEDIT", "HISTFILE", "HISTSIZE", "HOME", "IFS", "LANG",+ "LC_ALL", "LC_COLLATE", "LC_CTYPE", "LC_MESSAGES", "LC_MONETARY",+ "LC_NUMERIC", "LC_TIME", "MAIL", "MAILCHECK", "MAILPATH", "OLDPWD",+ "OPTARG", "OPTIND", "PATH", "PWD",+ -- Bash "BASH", "BASHOPTS", "BASHPID", "BASH_ALIASES", "BASH_ARGC", "BASH_ARGV", "BASH_ARGV0", "BASH_CMDS", "BASH_COMMAND",@@ -36,24 +46,20 @@ "BASH_VERSION", "COMP_CWORD", "COMP_KEY", "COMP_LINE", "COMP_POINT", "COMP_TYPE", "COMP_WORDBREAKS", "COMP_WORDS", "COPROC", "DIRSTACK", "EPOCHREALTIME", "EPOCHSECONDS", "EUID", "FUNCNAME", "GROUPS", "HISTCMD",- "HOSTNAME", "HOSTTYPE", "LINENO", "MACHTYPE", "MAPFILE", "OLDPWD",- "OPTARG", "OPTIND", "OSTYPE", "PIPESTATUS", "PPID", "PWD", "RANDOM",- "READLINE_ARGUMENT", "READLINE_LINE", "READLINE_MARK", "READLINE_POINT",- "REPLY", "SECONDS", "SHELLOPTS", "SHLVL", "SRANDOM", "UID", "BASH_COMPAT",- "BASH_ENV", "BASH_XTRACEFD", "CDPATH", "CHILD_MAX", "COLUMNS",- "COMPREPLY", "EMACS", "ENV", "EXECIGNORE", "FCEDIT", "FIGNORE",- "FUNCNEST", "GLOBIGNORE", "HISTCONTROL", "HISTFILE", "HISTFILESIZE",- "HISTIGNORE", "HISTSIZE", "HISTTIMEFORMAT", "HOME", "HOSTFILE", "IFS",- "IGNOREEOF", "INPUTRC", "INSIDE_EMACS", "LANG", "LC_ALL", "LC_COLLATE",- "LC_CTYPE", "LC_MESSAGES", "LC_MONETARY", "LC_NUMERIC", "LC_TIME",- "LINES", "MAIL", "MAILCHECK", "MAILPATH", "OPTERR", "PATH",- "POSIXLY_CORRECT", "PROMPT_COMMAND", "PROMPT_DIRTRIM", "PS0", "PS1",- "PS2", "PS3", "PS4", "SHELL", "TIMEFORMAT", "TMOUT", "TMPDIR",- "auto_resume", "histchars",+ "HOSTNAME", "HOSTTYPE", "MACHTYPE", "MAPFILE", "OSTYPE", "PIPESTATUS",+ "RANDOM", "READLINE_ARGUMENT", "READLINE_LINE", "READLINE_MARK",+ "READLINE_POINT", "REPLY", "SECONDS", "SHELLOPTS", "SHLVL", "SRANDOM",+ "UID", "BASH_COMPAT", "BASH_ENV", "BASH_XTRACEFD", "CHILD_MAX", "COLUMNS",+ "COMPREPLY", "EMACS", "EXECIGNORE", "FIGNORE", "FUNCNEST", "GLOBIGNORE",+ "HISTCONTROL", "HISTFILESIZE", "HISTIGNORE", "HISTTIMEFORMAT", "HOSTFILE",+ "IGNOREEOF", "INPUTRC", "INSIDE_EMACS", "LINES", "OPTERR",+ "POSIXLY_CORRECT", "PROMPT_COMMAND", "PROMPT_DIRTRIM", "PS0", "PS1", "PS2",+ "PS3", "PS4", "SHELL", "TIMEFORMAT", "TMOUT", "BASH_MONOSECONDS",+ "BASH_TRAPSIG", "GLOBSORT", "auto_resume", "histchars", -- Other "USER", "TZ", "TERM", "LOGNAME", "LD_LIBRARY_PATH", "LANGUAGE", "DISPLAY",- "HOSTNAME", "KRB5CCNAME", "XAUTHORITY"+ "HOSTNAME", "KRB5CCNAME", "LINENO", "PPID", "TMPDIR", "XAUTHORITY" -- Ksh , ".sh.version"@@ -75,7 +81,7 @@ "EPOCHREALTIME", "EPOCHSECONDS", "LINENO", "OPTIND", "PPID", "RANDOM", "READLINE_ARGUMENT", "READLINE_MARK", "READLINE_POINT", "SECONDS", "SHELLOPTS", "SHLVL", "SRANDOM", "UID", "COLUMNS", "HISTFILESIZE",- "HISTSIZE", "LINES"+ "HISTSIZE", "LINES", "BASH_MONOSECONDS", "BASH_TRAPSIG" -- shflags , "FLAGS_ERROR", "FLAGS_FALSE", "FLAGS_TRUE"@@ -100,31 +106,31 @@ "compress", "continue", "cp", "crontab", "csplit", "ctags", "cut", "cxref", "date", "dd", "delta", "df", "diff", "dirname", "dot", "du", "echo", "ed", "env", "eval", "ex", "exec", "exit", "expand",- "export", "expr", "fc", "fg", "file", "find", "fold", "fort77",- "fuser", "gencat", "get", "getconf", "getopts", "grep", "hash",+ "export", "expr", "fc", "fg", "file", "find", "fold", "fuser",+ "gencat", "get", "getconf", "getopts", "gettext", "grep", "hash", "head", "iconv", "ipcrm", "ipcs", "jobs", "join", "kill", "lex", "link", "ln", "locale", "localedef", "logger", "logname", "lp", "ls", "m4", "mailx", "make", "man", "mesg", "mkdir", "mkfifo",- "more", "mv", "newgrp", "nice", "nl", "nm", "nohup", "od", "paste",- "patch", "pathchk", "pax", "pr", "printf", "prs", "ps", "pwd",- "qalter", "qdel", "qhold", "qmove", "qmsg", "qrerun", "qrls",- "qselect", "qsig", "qstat", "qsub", "read", "readonly", "renice",- "return", "rm", "rmdel", "rmdir", "sact", "sccs", "sed", "set",- "sh", "shift", "sleep", "sort", "split", "strings", "strip", "stty",- "tabs", "tail", "talk", "tee", "test", "time", "times", "touch",- "tput", "tr", "trap", "tsort", "tty", "type", "ulimit", "umask",- "unalias", "uname", "uncompress", "unexpand", "unget", "uniq",- "unlink", "unset", "uucp", "uudecode", "uuencode", "uustat", "uux",- "val", "vi", "wait", "wc", "what", "who", "write", "xargs", "yacc",- "zcat"+ "more", "msgfmt", "mv", "newgrp", "ngettext", "nice", "nl", "nm",+ "nohup", "od", "paste", "patch", "pathchk", "pax", "pr", "printf",+ "prs", "ps", "pwd", "read", "readlink", "readonly", "realpath",+ "renice", "return", "rm", "rmdel", "rmdir", "sact", "sccs", "sed",+ "set", "sh", "shift", "sleep", "sort", "split", "strings", "strip",+ "stty", "tabs", "tail", "talk", "tee", "test", "time", "timeout",+ "times", "touch", "tput", "tr", "trap", "tsort", "tty", "type",+ "ulimit", "umask", "unalias", "uname", "uncompress", "unexpand",+ "unget", "uniq", "unlink", "unset", "uucp", "uudecode", "uuencode",+ "uustat", "uux", "val", "vi", "wait", "wc", "what", "who", "write",+ "xargs", "xgettext", "yacc", "zcat" ] nonReadingCommands = [ "alias", "basename", "bg", "cal", "cd", "chgrp", "chmod", "chown", "cp", "du", "echo", "export", "fg", "fuser", "getconf", "getopt", "getopts", "ipcrm", "ipcs", "jobs", "kill", "ln", "ls",- "locale", "mv", "printf", "ps", "pwd", "renice", "rm", "rmdir",- "set", "sleep", "touch", "trap", "ulimit", "unalias", "uname"+ "locale", "mv", "printf", "ps", "pwd", "readlink", "realpath",+ "renice", "rm", "rmdir", "set", "sleep", "touch", "trap", "ulimit",+ "unalias", "uname" ] sampleWords = [@@ -150,20 +156,47 @@ "-o", "-v", "-R" ] +supportedShellDialects = [+ "sh", "bash", "dash", "ksh", "busybox"+ ]+ shellForExecutable :: String -> Maybe Shell shellForExecutable name = case name of "sh" -> return Sh "bash" -> return Bash "bats" -> return Bash+ "busybox" -> return BusyboxSh -- Used for directives and --shell=busybox+ "busybox sh" -> return BusyboxSh+ "busybox ash" -> return BusyboxSh "dash" -> return Dash "ash" -> return Dash -- There's also a warning for this. "ksh" -> return Ksh "ksh88" -> return Ksh "ksh93" -> return Ksh+ "oksh" -> return Ksh _ -> Nothing +shellFromAnnotations :: [Annotation] -> String -> Maybe Shell+shellFromAnnotations annotations executable =+ shellForExecutable $ headOrDefault executable [s | ShellOverride s <- annotations]++shellFromFilename :: String -> Maybe Shell+shellFromFilename filename = listToMaybe candidates+ where+ shellExtensions = [(".ksh", Ksh)+ ,(".bash", Bash)+ ,(".bats", Bash)+ ,(".dash", Dash)+ ,(".envrc", Bash)]+ -- The `.sh` is too generic to determine the shell:+ -- We fallback to Bash in this case and emit SC2148 if there is no shebang+ candidates =+ [sh | (ext,sh) <- shellExtensions, ext `isSuffixOf` filename]+ flagsForRead = "sreu:n:N:i:p:a:t:" flagsForMapfile = "d:n:O:s:u:C:c:t" declaringCommands = ["local", "declare", "export", "readonly", "typeset", "let"]++privilegeElevationCommands = ["sudo", "doas", "run0"]
src/ShellCheck/Debug.hs view
@@ -74,7 +74,7 @@ -} -module ShellCheck.Debug () where+module ShellCheck.Debug where import ShellCheck.Analyzer import ShellCheck.AST@@ -117,7 +117,8 @@ cfgParams :: CFGParameters cfgParams = CFGParameters { cfLastpipe = False,- cfPipefail = False+ cfPipefail = False,+ cfSourceAsBoundary = False } -- An example script to play with
+ src/ShellCheck/EditorConfig.hs view
@@ -0,0 +1,468 @@+{-+ Copyright 2012-2024 Vidar Holen++ This file is part of ShellCheck.+ https://www.shellcheck.net++ ShellCheck is free software: you can redistribute it and/or modify+ it under the terms of the GNU General Public License as published by+ the Free Software Foundation, either version 3 of the License, or+ (at your option) any later version.++ ShellCheck is distributed in the hope that it will be useful,+ but WITHOUT ANY WARRANTY; without even the implied warranty of+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ GNU General Public License for more details.++ You should have received a copy of the GNU General Public License+ along with this program. If not, see <https://www.gnu.org/licenses/>.+-}++{-# LANGUAGE TemplateHaskell #-}+-- Minimal support for reading shellcheck directives from EditorConfig+-- style files (https://editorconfig.org/). Only the `shellcheck.*` keys+-- of sections whose glob matches the file being checked are extracted,+-- and turned into the same "key=value" directive syntax that is used in+-- .shellcheckrc files.+module ShellCheck.EditorConfig (parseEditorConfig, isEditorConfigRoot, invalidRootLines, invalidDirectiveLines, editorConfigDirectives, globToRegexString, runTests) where++import Data.Char+import Data.List+import Data.Maybe++import ShellCheck.Data (shellForExecutable)+import ShellCheck.Regex++import Test.QuickCheck++-- Given the contents of an EditorConfig style file and the name of the+-- file being checked, return the shellcheck directives (as a+-- "key=value\n" delimited blob, suitable for feeding into the same+-- parser as .shellcheckrc) found in matching sections.+--+-- As per the EditorConfig spec, files are read top to bottom and+-- properties from later sections override those from earlier ones+-- (for the same key), so on conflicts the last matching section wins.+parseEditorConfig :: String -> FilePath -> String+parseEditorConfig contents name =+ renderDirectives . lastWins . mapMaybe usable $ allDirectives name sections+ where+ -- Render each directive at its original line in the config file, so+ -- that any parse error (SC1134) is reported at the correct line.+ renderDirectives = snd . foldl step (0, "")+ step (prevLine, out) (line, key, value) =+ (line, out ++ replicate (line - prevLine - 1) '\n' ++ key ++ "=" ++ value ++ "\n")++ -- Keep only the last occurrence of each key, preserving the+ -- relative order of the remaining (first-seen) entries.+ lastWins = reverse . nubBy (\a b -> keyOf a == keyOf b) . reverse+ where+ keyOf (_, key, _) = key++ usable (line, key, value) =+ if isUsableDirective key value+ then Just (line, key, value)+ else Nothing++ ls = lines contents+ sections = splitSections 1 ls++ splitSections _ [] = []+ splitSections n (l:rest) =+ case parseHeader l of+ Just pat ->+ let (body, rest') = break (isJust . parseHeader) rest+ in (pat, zip [n+1..] body) : splitSections (n + 1 + length body) rest'+ Nothing -> splitSections (n+1) rest++ parseHeader l =+ let t = trim (dropLineComment l)+ in case t of+ ('[':cs@(_:_)) | last cs == ']' -> Just (init cs)+ _ -> Nothing++ -- All 'shellcheck.*' directives (as (line, key, value) tuples) found+ -- in sections whose glob matches the file being checked.+ allDirectives name = concatMap (sectionDirectives name)++ sectionDirectives name (pat, body) =+ if matchesGlob pat name+ then mapMaybe toDirectivePair body+ else []++ toDirectivePair (line, l) =+ case break (== '=') (trim (dropLineComment l)) of+ (key, '=':value) ->+ let key' = trim key+ value' = trim value+ in if "shellcheck." `isPrefixOf` key'+ then Just (line, drop (length "shellcheck.") key', value')+ else Nothing+ _ -> Nothing++ -- Only emit directives that the .shellcheckrc parser can handle+ -- unambiguously. Unknown shells (e.g. 'shellcheck.shell=zsh') would+ -- otherwise silently suppress the SC2148 "unknown shell" warning, so+ -- they are dropped here and reported via invalidDirectiveLines.+ -- Values containing '#' or ';' anywhere (not just at the start) are+ -- also dropped and reported: EditorConfig has no inline comments, so+ -- such a value is otherwise silently truncated by the .shellcheckrc+ -- parser's trailing-comment handling (e.g. both 'disable=#abc' and+ -- 'disable=SC2148 #abc' would silently lose the part from '#'+ -- onwards). Empty values for other keys are simply skipped (no-op):+ -- the rc parser would silently accept them anyway.+ isUsableDirective "shell" value = null value || isJust (shellForExecutable value)+ isUsableDirective _ value = not (null value) && not (hasCommentMarker value)++ hasCommentMarker = any (`elem` "#;")++-- Returns the 1-based line numbers of invalid 'shellcheck.*' directives,+-- i.e.:+-- * 'shellcheck.shell=<x>' where <x> is a non-empty, unknown shell+-- (e.g. 'zsh'), which would otherwise silently suppress the SC2148+-- "unknown shell" warning;+-- * any 'shellcheck.<key>=<value>' whose (trimmed) value contains '#'+-- or ';' anywhere, since EditorConfig does not allow inline comments+-- and such a value is otherwise silently truncated by the+-- .shellcheckrc parser's trailing-comment handling (e.g. both+-- 'disable=#abc' and 'disable=SC2148 #abc' would silently lose the+-- part from '#' onwards). Plain empty values are not reported here:+-- they are simply no-ops.+-- Only directives in sections whose glob matches the file are reported.+invalidDirectiveLines :: String -> FilePath -> [Int]+invalidDirectiveLines contents name =+ [ line | (line, key, value) <- allDirectives name sections+ , isInvalidDirective key value ]+ where+ isInvalidDirective "shell" value = not (null value) && isNothing (shellForExecutable value)+ isInvalidDirective _ value = hasCommentMarker value++ hasCommentMarker = any (`elem` "#;")++ sections = splitSections 1 (lines contents)++ splitSections _ [] = []+ splitSections n (l:rest) =+ case parseHeader l of+ Just pat ->+ let (body, rest') = break (isJust . parseHeader) rest+ in (pat, zip [n+1..] body) : splitSections (n + 1 + length body) rest'+ Nothing -> splitSections (n+1) rest++ parseHeader l =+ let t = trim (dropLineComment l)+ in case t of+ ('[':cs@(_:_)) | last cs == ']' -> Just (init cs)+ _ -> Nothing++ allDirectives name = concatMap (sectionDirectives name)++ sectionDirectives name (pat, body) =+ if matchesGlob pat name+ then mapMaybe toDirectivePair body+ else []++ toDirectivePair (line, l) =+ case break (== '=') (trim (dropLineComment l)) of+ (key, '=':value) ->+ let key' = trim key+ value' = trim value+ in if "shellcheck." `isPrefixOf` key'+ then Just (line, drop (length "shellcheck.") key', value')+ else Nothing+ _ -> Nothing++-- Build the directive blob contributed by a single EditorConfig file for+-- the given file being checked. Returns Nothing if the file contributes+-- nothing (no matching section, or only empty values). Returns a blob of+-- "key=value\n" directives when the matching sections are valid, or a+-- single rejected line at the position of any invalid 'shellcheck.*'+-- directive so that the .shellcheckrc parser reports it as SC1134.+editorConfigDirectives :: String -> FilePath -> Maybe String+editorConfigDirectives contents name =+ let badLines = invalidDirectiveLines contents name+ in if not (null badLines)+ then Just . unlines $ map rejectedLine (nub (sort badLines))+ else let result = parseEditorConfig contents name+ in if null result then Nothing else Just result+ where+ rejectedLine n = replicate (n - 1) '\n' ++ "invalid editorconfig value"++-- Does the top-level (pre-section) part of an EditorConfig file+-- declare "root = true"? Per the spec, this stops the search for+-- further EditorConfig files in parent directories.+isEditorConfigRoot :: String -> Bool+isEditorConfigRoot contents =+ any (== Just "true") . map rootValue $ preSectionLines contents+ where+ isSectionHeader l =+ case trim (dropLineComment l) of+ ('[':cs@(_:_)) -> last cs == ']'+ _ -> False+ preSectionLines = takeWhile (not . isSectionHeader) . lines++ rootValue l =+ case break (== '=') (trim (dropLineComment l)) of+ (key, '=':value) | map toLower (trim key) == "root" ->+ Just (map toLower (trim value))+ _ -> Nothing++-- Returns the 1-based line numbers of invalid 'root' declarations,+-- i.e. root values other than true/false (such as 'root =').+invalidRootLines :: String -> [Int]+invalidRootLines contents =+ [ n | (n, l) <- zip [1..] (preSectionLines contents)+ , case rootValue l of+ Just value -> value `notElem` ["true", "false"]+ Nothing -> False ]+ where+ isSectionHeader l =+ case trim (dropLineComment l) of+ ('[':cs@(_:_)) -> last cs == ']'+ _ -> False+ preSectionLines = takeWhile (not . isSectionHeader) . lines++ rootValue l =+ case break (== '=') (trim (dropLineComment l)) of+ (key, '=':value) | map toLower (trim key) == "root" ->+ Just (map toLower (trim value))+ _ -> Nothing++-- EditorConfig does not allow inline comments; '#' and ';' starting+-- on the first non-whitespace character denote a full-line comment.+-- Lines not starting with '#' or ';' must be returned verbatim.+dropLineComment l =+ case dropWhile isSpace l of+ ('#':_) -> ""+ (';':_) -> ""+ _ -> l++trim :: String -> String+trim = dropWhileEnd isSpace . dropWhile isSpace++-- Does the (relative path of the) file match the given EditorConfig glob?+matchesGlob :: String -> FilePath -> Bool+matchesGlob pattern name =+ name `matches` mkRegex (globToRegexString pattern)++-- Translate an EditorConfig glob pattern into an anchored regex string.+-- Per the spec, patterns without a path separator are matched against+-- the file at any depth (as if prefixed with "**/").+globToRegexString :: String -> String+globToRegexString pattern = "^" ++ prefix ++ go pattern ++ "$"+ where+ prefix = if '/' `elem` pattern then "" else "(.*/)?"++ go [] = ""+ go ('*':'*':rest) = ".*" ++ go rest+ go ('*':rest) = "[^/]*" ++ go rest+ go ('?':rest) = "[^/]" ++ go rest+ go ('[':rest) =+ let (cls, rest') = break (== ']') rest+ in case rest' of+ (']':rest'') -> "[" ++ translateClass cls ++ "]" ++ go rest''+ _ -> "\\[" ++ go rest+ go ('{':rest) =+ case findMatchingBrace rest of+ Just (body, rest'') ->+ buildAlternation (map go (braceAlternatives body)) ++ go rest''+ _ -> "\\{" ++ go rest+ go (c:rest)+ | c `elem` regexSpecials = ['\\', c] ++ go rest+ | otherwise = c : go rest++ regexSpecials = ".\\+()^$|"++ translateClass ('!':cs) = '^' : escapeClass cs+ translateClass cs = escapeClass cs+ escapeClass = concatMap (\c -> if c == '\\' then "\\\\" else [c])++ -- Scan past a balanced '{' ... '}' pair, returning the contents of+ -- the braces (with any nested braces verbatim) and the remainder.+ -- Returns Nothing if the braces are unbalanced.+ findMatchingBrace = goBrace 1 ""+ where+ goBrace _ _ "" = Nothing+ goBrace d acc (c:cs)+ | c == '}' =+ if d == 1 then Just (reverse acc, cs)+ else goBrace (d - 1) (c:acc) cs+ | c == '{' = goBrace (d + 1) (c:acc) cs+ | otherwise = goBrace d (c:acc) cs++ -- Wrap a list of regex alternatives in an anchored group. Empty+ -- alternatives are handled so the result is always a valid regex:+ -- * all empty -> "" (the whole group matches the empty string)+ -- * some empty -> "(a|b)?" (the group is optional)+ -- * none empty -> "(a|b|c)"+ buildAlternation alts+ | all null alts = ""+ | any null alts = "(" ++ intercalate "|" (filter (not . null) alts) ++ ")?"+ | otherwise = "(" ++ intercalate "|" alts ++ ")"++ -- Expand EditorConfig brace alternatives. Besides the comma+ -- separated form, EditorConfig supports numeric ranges like+ -- '{1..3}' which match any integer in the range. Commas inside+ -- nested braces (e.g. 'ba{r,z}') are not treated as separators.+ braceAlternatives body =+ case break (== '.') body of+ (fromStr, '.':'.':toStr)+ | Just from <- readInt fromStr+ , Just to <- readInt toStr ->+ map show $+ if from < to+ then [from..to]+ else []+ _ -> splitTopLevelCommas body++ -- Split on commas, but ignore commas that appear inside nested+ -- '{...}' pairs so that 'a,b{c,d}' yields ["a", "b{c,d}"].+ splitTopLevelCommas = go 0 ""+ where+ go _ acc "" = [reverse acc]+ go d acc (c:cs)+ | c == '{' = go (d + 1) (c:acc) cs+ | c == '}' = go (max 0 (d - 1)) (c:acc) cs+ | c == ',' && d == 0 = reverse acc : go 0 "" cs+ | otherwise = go d (c:acc) cs++ readInt s =+ case reads s :: [(Int, String)] of+ [(n, "")] -> Just n+ _ -> Nothing++prop_globStar = matchesGlob "*.ebuild" "foo.ebuild"+prop_globBraceExt = matchesGlob "*.{ebuild,eclass}" "foo.eclass"+prop_globBraceExt2 = matchesGlob "*.{ebuild,eclass}" "foo.ebuild"+prop_globBraceName = matchesGlob "{PKGBUILD,APKBUILD}" "PKGBUILD"+prop_globBraceName2 = matchesGlob "{PKGBUILD,APKBUILD}" "APKBUILD"+prop_globNoMatch = not $ matchesGlob "*.ebuild" "foo.txt"+prop_globQuestion = matchesGlob "foo?.sh" "food.sh"+prop_globClass = matchesGlob "foo[0-9].sh" "foo1.sh"+prop_globClassNeg = not $ matchesGlob "foo[!0-9].sh" "foo1.sh"+-- Patterns without a path separator should match at any depth.+prop_globAnyDepth = matchesGlob "*.sh" "sub/dir/foo.sh"+prop_globAnyDepthPlain = matchesGlob "foo" "sub/foo"+-- Patterns with a path separator are only matched against the full+-- relative path.+prop_globWithSlashNoMatch = not $ matchesGlob "sub/*.sh" "other/foo.sh"+prop_globWithSlashMatch = matchesGlob "sub/*.sh" "sub/foo.sh"+-- Numeric range expansion+prop_globRange = matchesGlob "file{1..3}.sh" "file2.sh"+prop_globRangeStart = matchesGlob "file{1..3}.sh" "file1.sh"+prop_globRangeEnd = matchesGlob "file{1..3}.sh" "file3.sh"+prop_globRangeNoMatch = not $ matchesGlob "file{1..3}.sh" "file4.sh"+prop_globRangeNegative = matchesGlob "file{-2..0}.sh" "file-1.sh"+prop_globRangeDescending = not $ matchesGlob "file{3..1}.sh" "file2.sh"+prop_globLiteralDots = not $ matchesGlob "file{1..3}.sh" "file1..3.sh"+-- Empty brace alternatives (e.g. 'foo{,bar}') make the group optional:+-- 'foo' and 'foobar' both match.+prop_globBraceEmptyAlt = matchesGlob "foo{,bar}" "foo"+prop_globBraceEmptyAlt2 = matchesGlob "foo{,bar}" "foobar"+prop_globBraceEmptyAltNoMatch = not $ matchesGlob "foo{,bar}" "foobaz"+-- Nested braces: '{foo,ba{r,z}}' matches foo, bar and baz.+prop_globBraceNested1 = matchesGlob "{foo,ba{r,z}}" "foo"+prop_globBraceNested2 = matchesGlob "{foo,ba{r,z}}" "bar"+prop_globBraceNested3 = matchesGlob "{foo,ba{r,z}}" "baz"+prop_globBraceNestedNoMatch = not $ matchesGlob "{foo,ba{r,z}}" "baq"++prop_parseEditorConfig1 =+ parseEditorConfig "[*.{ebuild,eclass}]\nshellcheck.shell=bash\nshellcheck.disable=SC2034\n" "foo.ebuild"+ == "\nshell=bash\ndisable=SC2034\n"+prop_parseEditorConfig2 =+ parseEditorConfig "[*.{ebuild,eclass}]\nshellcheck.shell=bash\n" "foo.txt" == ""+prop_parseEditorConfig3 =+ parseEditorConfig "[{PKGBUILD,APKBUILD}]\nshellcheck.disable=SC2034\n" "PKGBUILD" == "\ndisable=SC2034\n"+prop_parseEditorConfig4 =+ parseEditorConfig "root = true\n[*.sh]\nindent_style = space\nshellcheck.shell=bash\n" "foo.sh"+ == "\n\n\nshell=bash\n"+-- A later, more specific section overrides an earlier, more general+-- one for the same key.+prop_parseEditorConfig5 =+ parseEditorConfig "[*]\nshellcheck.shell=sh\n\n[foo]\nshellcheck.shell=bash\n" "foo"+ == "\n\n\n\nshell=bash\n"+-- Non-conflicting keys from earlier and later sections are all kept.+prop_parseEditorConfig6 =+ parseEditorConfig "[*]\nshellcheck.shell=sh\n\n[foo]\nshellcheck.disable=SC2034\n" "foo"+ == "\nshell=sh\n\n\ndisable=SC2034\n"+-- An unsupported shell is not emitted as a usable directive; instead its+-- line is reported via invalidDirectiveLines so the caller can reject it.+prop_parseEditorConfigUnknownShell =+ parseEditorConfig "[*]\nshellcheck.shell=zsh\n" "foo" == ""+prop_parseEditorConfigEmptyShell =+ parseEditorConfig "[*]\nshellcheck.shell=\n" "foo" == "\nshell=\n"+prop_parseEditorConfigEmptyDisable =+ parseEditorConfig "[*]\nshellcheck.disable=\n" "foo" == ""+-- A '#' embedded anywhere in the value (not just at the start) makes it+-- invalid too, since EditorConfig has no inline comments and the+-- .shellcheckrc parser would otherwise silently truncate it at the '#'.+prop_parseEditorConfigEmbeddedComment =+ parseEditorConfig "[*]\nshellcheck.disable=SC2148 #abc\n" "foo" == ""+-- EditorConfig does not allow inline comments, so a trailing '# ...'+-- makes the value invalid (the .shellcheckrc parser's+-- shellForExecutable lookup fails on the embedded text), and the+-- directive is dropped. It is reported via invalidDirectiveLines.+prop_parseEditorConfigInlineComment =+ parseEditorConfig "[*]\nshellcheck.shell=bash # inline\n" "foo" == ""+-- Full-line comments starting on first non-ws char are stripped.+prop_parseEditorConfigLineComment =+ parseEditorConfig "[*]\n# shellcheck.shell=bash\n" "foo" == ""+prop_parseEditorConfigSemicolonComment =+ parseEditorConfig "[*]\n; shellcheck.shell=bash\n" "foo" == ""+-- Empty brace alternative makes the glob group optional; 'foo' matches+-- '[foo{,bar}]'.+prop_parseEditorConfigBraceEmpty =+ parseEditorConfig "[foo{,bar}]\nshellcheck.shell=sh\n" "foo" == "\nshell=sh\n"+-- Nested braces are expanded correctly; 'baz' matches+-- '[{foo,ba{r,z}}]'.+prop_parseEditorConfigBraceNested =+ parseEditorConfig "[{foo,ba{r,z}}]\nshellcheck.shell=sh\n" "baz" == "\nshell=sh\n"+prop_isEditorConfigRootEmpty = not $ isEditorConfigRoot "root =\n"+prop_isEditorConfigRootFalse = not $ isEditorConfigRoot "root = false\n"+prop_isEditorConfigRootTrue = isEditorConfigRoot "root = TRUE\n"+prop_invalidRootLinesEmpty = invalidRootLines "root =\n" == [1]+prop_invalidRootLinesTrue = invalidRootLines "root = true\n" == []+prop_invalidRootLinesFalse = invalidRootLines "root = false\n" == []+prop_invalidRootLinesInSection =+ invalidRootLines "[*]\nroot = true\n" == []+-- An unsupported non-empty shell is reported at its line.+prop_invalidDirectiveLinesUnknownShell =+ invalidDirectiveLines "[*]\nshellcheck.shell=zsh\n" "foo" == [2]+-- An empty shell is valid (the rc parser rejects it), so no error.+prop_invalidDirectiveLinesEmptyShell =+ invalidDirectiveLines "[*]\nshellcheck.shell=\n" "foo" == []+-- A known shell is fine.+prop_invalidDirectiveLinesKnownShell =+ invalidDirectiveLines "[*]\nshellcheck.shell=bash\n" "foo" == []+-- A '#'-prefixed value is reported (EditorConfig has no inline comments).+prop_invalidDirectiveLinesHashValue =+ invalidDirectiveLines "[foo]\nshellcheck.disable = #abc\n" "foo" == [2]+-- A ';'-prefixed value is reported too.+prop_invalidDirectiveLinesSemicolonValue =+ invalidDirectiveLines "[foo]\nshellcheck.disable = ;abc\n" "foo" == [2]+-- A '#' embedded anywhere in the value (not just at the start) is+-- reported too: previously this was silently accepted, since the+-- .shellcheckrc parser would treat everything from the '#' onwards as a+-- trailing comment (e.g. this used to disable SC2148 without warning).+prop_invalidDirectiveLinesEmbeddedHashValue =+ invalidDirectiveLines "[foo]\nshellcheck.disable = SC2148 #abc\n" "foo" == [2]+prop_invalidDirectiveLinesEmbeddedSemicolonValue =+ invalidDirectiveLines "[foo]\nshellcheck.disable = SC2148 ;abc\n" "foo" == [2]+-- A plain empty value (no comment marker) is not reported: it is simply+-- a no-op, unlike a value that was truncated down to empty by a leading+-- comment marker.+prop_invalidDirectiveLinesEmptyValueNotInvalid =+ invalidDirectiveLines "[foo]\nshellcheck.disable =\n" "foo" == []+-- A plain invalid value (no comment marker) is not reported here; it is+-- rejected by the .shellcheckrc parser as SC1134 instead.+prop_invalidDirectiveLinesPlainValue =+ invalidDirectiveLines "[foo]\nshellcheck.disable = abc\n" "foo" == []+-- Directives in non-matching sections are ignored.+prop_invalidDirectiveLinesNoMatch =+ invalidDirectiveLines "[*.txt]\nshellcheck.shell=zsh\n" "foo" == []+-- Only the matching section's invalid directive is reported.+prop_invalidDirectiveLinesMatchingSection =+ invalidDirectiveLines "[*.txt]\nshellcheck.shell=zsh\n[foo]\nshellcheck.shell=bash\n" "foo" == []++return []+runTests = $quickCheckAll
src/ShellCheck/Formatter/CheckStyle.hs view
@@ -24,8 +24,8 @@ import Data.Char import Data.List-import GHC.Exts import System.IO+import qualified Data.List.NonEmpty as NE format :: IO Formatter format = return Formatter {@@ -45,12 +45,12 @@ else mapM_ outputGroup fileGroups where comments = crComments cr- fileGroups = groupWith sourceFile comments+ fileGroups = NE.groupWith sourceFile comments outputGroup group = do- let filename = sourceFile (head group)+ let filename = sourceFile (NE.head group) result <- siReadFile sys (Just True) filename let contents = either (const "") id result- outputFile filename contents group+ outputFile filename contents (NE.toList group) outputFile filename contents warnings = do let comments = makeNonVirtual warnings contents
src/ShellCheck/Formatter/Diff.hs view
@@ -191,11 +191,17 @@ let (last, rest) = splitAt 1 $ reverse x in (reverse rest, last) +-- git patch does not like `\` on Windows+normalizePath path =+ case path of+ c:rest -> (if c == pathSeparator then '/' else c) : normalizePath rest+ [] -> []+ formatDoc color (DiffDoc name lf regions) = let (most, last) = splitLast regions in- (color bold $ "--- " ++ ("a" </> name)) ++ "\n" ++- (color bold $ "+++ " ++ ("b" </> name)) ++ "\n" +++ (color bold $ "--- " ++ (normalizePath $ "a" </> name)) ++ "\n" +++ (color bold $ "+++ " ++ (normalizePath $ "b" </> name)) ++ "\n" ++ concatMap (formatRegion color LinefeedOk) most ++ concatMap (formatRegion color lf) last
src/ShellCheck/Formatter/GCC.hs view
@@ -23,8 +23,8 @@ import ShellCheck.Formatter.Format import Data.List-import GHC.Exts import System.IO+import qualified Data.List.NonEmpty as NE format :: IO Formatter format = return Formatter {@@ -39,13 +39,13 @@ outputAll cr sys = mapM_ f groups where comments = crComments cr- groups = groupWith sourceFile comments- f :: [PositionedComment] -> IO ()+ groups = NE.groupWith sourceFile comments+ f :: NE.NonEmpty PositionedComment -> IO () f group = do- let filename = sourceFile (head group)+ let filename = sourceFile (NE.head group) result <- siReadFile sys (Just True) filename let contents = either (const "") id result- outputResult filename contents group+ outputResult filename contents (NE.toList group) outputResult filename contents warnings = do let comments = makeNonVirtual warnings contents
src/ShellCheck/Formatter/JSON1.hs view
@@ -27,9 +27,9 @@ import Data.Aeson import Data.IORef import Data.Monoid-import GHC.Exts import System.IO import qualified Data.ByteString.Lazy.Char8 as BL+import qualified Data.List.NonEmpty as NE format :: IO Formatter format = do@@ -114,13 +114,13 @@ collectResult ref cr sys = mapM_ f groups where comments = crComments cr- groups = groupWith sourceFile comments- f :: [PositionedComment] -> IO ()+ groups = NE.groupWith sourceFile comments+ f :: NE.NonEmpty PositionedComment -> IO () f group = do- let filename = sourceFile (head group)+ let filename = sourceFile (NE.head group) result <- siReadFile sys (Just True) filename let contents = either (const "") id result- let comments' = makeNonVirtual comments contents+ let comments' = makeNonVirtual (NE.toList group) contents deepseq comments' $ modifyIORef ref (\x -> comments' ++ x) finish ref = do
src/ShellCheck/Formatter/TTY.hs view
@@ -17,7 +17,7 @@ You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. -}-module ShellCheck.Formatter.TTY (format) where+module ShellCheck.Formatter.TTY (format, wikiLink) where import ShellCheck.Fixer import ShellCheck.Interface@@ -31,9 +31,9 @@ import Data.IORef import Data.List import Data.Maybe-import GHC.Exts import System.IO import System.Info+import qualified Data.List.NonEmpty as NE wikiLink = "https://www.shellcheck.net/wiki/" @@ -117,19 +117,19 @@ color <- getColorFunc $ foColorOption options let comments = crComments result appendComments ref comments (fromIntegral $ foWikiLinkCount options)- let fileGroups = groupWith sourceFile comments+ let fileGroups = NE.groupWith sourceFile comments mapM_ (outputForFile color sys) fileGroups outputForFile color sys comments = do- let fileName = sourceFile (head comments)+ let fileName = sourceFile (NE.head comments) result <- siReadFile sys (Just True) fileName let contents = either (const "") id result let fileLinesList = lines contents let lineCount = length fileLinesList let fileLines = listArray (1, lineCount) fileLinesList- let groups = groupWith lineNo comments+ let groups = NE.groupWith lineNo comments forM_ groups $ \commentsForLine -> do- let lineNum = fromIntegral $ lineNo (head commentsForLine)+ let lineNum = fromIntegral $ lineNo (NE.head commentsForLine) let line = if lineNum < 1 || lineNum > lineCount then "" else fileLines ! fromIntegral lineNum@@ -139,7 +139,7 @@ putStrLn (color "source" line) forM_ commentsForLine $ \c -> putStrLn $ color (severityText c) $ cuteIndent c putStrLn ""- showFixedString color commentsForLine (fromIntegral lineNum) fileLines+ showFixedString color (toList commentsForLine) (fromIntegral lineNum) fileLines -- Pick out only the lines necessary to show a fix in action sliceFile :: Fix -> Array Int String -> (Fix, Array Int String)@@ -169,7 +169,7 @@ -- and/or other unrelated lines. let (excerptFix, excerpt) = sliceFile mergedFix fileLines -- in the spirit of error prone- putStrLn $ color "message" "Did you mean: "+ putStrLn $ color "message" "Did you mean:" putStrLn $ unlines $ applyFix excerptFix excerpt cuteIndent :: PositionedComment -> String
src/ShellCheck/Interface.hs view
@@ -1,5 +1,5 @@ {-- Copyright 2012-2019 Vidar Holen+ Copyright 2012-2024 Vidar Holen This file is part of ShellCheck. https://www.shellcheck.net@@ -21,14 +21,14 @@ module ShellCheck.Interface ( SystemInterface(..)- , CheckSpec(csFilename, csScript, csCheckSourced, csIncludedWarnings, csExcludedWarnings, csShellTypeOverride, csMinSeverity, csIgnoreRC, csOptionalChecks)+ , CheckSpec(csFilename, csScript, csCheckSourced, csIncludedWarnings, csExcludedWarnings, csShellTypeOverride, csMinSeverity, csIgnoreRC, csExtendedAnalysis, csOptionalChecks) , CheckResult(crFilename, crComments) , ParseSpec(psFilename, psScript, psCheckSourced, psIgnoreRC, psShellTypeOverride) , ParseResult(prComments, prTokenPositions, prRoot)- , AnalysisSpec(asScript, asShellType, asFallbackShell, asExecutionMode, asCheckSourced, asTokenPositions, asOptionalChecks)+ , AnalysisSpec(asScript, asShellType, asFallbackShell, asExecutionMode, asCheckSourced, asTokenPositions, asExtendedAnalysis, asOptionalChecks) , AnalysisResult(arComments) , FormatterOptions(foColorOption, foWikiLinkCount)- , Shell(Ksh, Sh, Bash, Dash)+ , Shell(Ksh, Sh, Bash, Dash, BusyboxSh) , ExecutionMode(Executed, Sourced) , ErrorMessage , Code@@ -37,13 +37,15 @@ , Comment(cSeverity, cCode, cMessage) , PositionedComment(pcStartPos , pcEndPos , pcComment, pcFix) , ColorOption(ColorAuto, ColorAlways, ColorNever)+ , ExtendedAnalysisMode(ExtendedAnalysisNone, ExtendedAnalysisLocal, ExtendedAnalysisFull) , TokenComment(tcId, tcComment, tcFix) , emptyCheckResult- , newParseResult- , newAnalysisSpec , newAnalysisResult+ , newAnalysisSpec , newFormatterOptions+ , newParseResult , newPosition+ , newSystemInterface , newTokenComment , mockedSystemInterface , mockRcFile@@ -56,7 +58,7 @@ , InsertionPoint(InsertBefore, InsertAfter) , Replacement(repStartPos, repEndPos, repString, repPrecedence, repInsertionPoint) , newReplacement- , CheckDescription(cdName, cdDescription, cdPositive, cdNegative)+ , CheckDescription(cdName, cdId, cdDescription, cdPositive, cdNegative) , newCheckDescription ) where @@ -99,6 +101,7 @@ csIncludedWarnings :: Maybe [Integer], csShellTypeOverride :: Maybe Shell, csMinSeverity :: Severity,+ csExtendedAnalysis :: Maybe ExtendedAnalysisMode, csOptionalChecks :: [String] } deriving (Show, Eq) @@ -123,6 +126,7 @@ csIncludedWarnings = Nothing, csShellTypeOverride = Nothing, csMinSeverity = StyleC,+ csExtendedAnalysis = Nothing, csOptionalChecks = [] } @@ -135,6 +139,14 @@ psShellTypeOverride = Nothing } +newSystemInterface :: Monad m => SystemInterface m+newSystemInterface =+ SystemInterface {+ siReadFile = \_ _ -> return $ Left "Not implemented",+ siFindSource = \_ _ _ name -> return name,+ siGetConfig = \_ -> return Nothing+ }+ -- Parser input and output data ParseSpec = ParseSpec { psFilename :: String,@@ -165,6 +177,7 @@ asExecutionMode :: ExecutionMode, asCheckSourced :: Bool, asOptionalChecks :: [String],+ asExtendedAnalysis :: Maybe ExtendedAnalysisMode, asTokenPositions :: Map.Map Id (Position, Position) } @@ -175,6 +188,7 @@ asExecutionMode = Executed, asCheckSourced = False, asOptionalChecks = [],+ asExtendedAnalysis = Nothing, asTokenPositions = Map.empty } @@ -199,6 +213,7 @@ data CheckDescription = CheckDescription { cdName :: String,+ cdId :: [Integer], cdDescription :: String, cdPositive :: String, cdNegative :: String@@ -206,13 +221,14 @@ newCheckDescription = CheckDescription { cdName = "",+ cdId = [], cdDescription = "", cdPositive = "", cdNegative = "" } -- Supporting data types-data Shell = Ksh | Sh | Bash | Dash deriving (Show, Eq)+data Shell = Ksh | Sh | Bash | Dash | BusyboxSh deriving (Show, Eq) data ExecutionMode = Executed | Sourced deriving (Show, Eq) type ErrorMessage = String@@ -309,9 +325,16 @@ | ColorNever deriving (Ord, Eq, Show) +-- The scope of the data-flow ("extended") analysis+data ExtendedAnalysisMode =+ ExtendedAnalysisNone -- No data-flow analysis.+ | ExtendedAnalysisLocal -- Dataflow analysis stops at 'source' boundaries+ | ExtendedAnalysisFull -- Whole-program: data flow is followed into sourced files.+ deriving (Ord, Eq, Show)+ -- For testing mockedSystemInterface :: [(String, String)] -> SystemInterface Identity-mockedSystemInterface files = SystemInterface {+mockedSystemInterface files = (newSystemInterface :: SystemInterface Identity) { siReadFile = rf, siFindSource = fs, siGetConfig = const $ return Nothing@@ -326,4 +349,3 @@ mockRcFile rcfile mock = mock { siGetConfig = const . return $ Just (".shellcheckrc", rcfile) }-
src/ShellCheck/Parser.hs view
@@ -21,6 +21,7 @@ {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiWayIf #-}+{-# LANGUAGE NondecreasingIndentation #-} module ShellCheck.Parser (parseScript, runTests) where import ShellCheck.AST@@ -46,7 +47,9 @@ import Text.Parsec.Pos import qualified Control.Monad.Reader as Mr import qualified Control.Monad.State as Ms+import qualified Data.List.NonEmpty as NE import qualified Data.Map.Strict as Map+import Debug.Trace import Test.QuickCheck.All (quickCheckAll) @@ -65,10 +68,14 @@ doubleQuote = char '"' variableStart = upper <|> lower <|> oneOf "_" variableChars = upper <|> lower <|> digit <|> oneOf "_"--- Chars to allow in function names-functionChars = variableChars <|> oneOf ":+?-./^@,"+-- Chars to allow function names to start with+functionStartChars = variableChars <|> oneOf ":+?-./^@,"+-- Chars to allow inside function names+functionChars = variableChars <|> oneOf "#:+?-./^@,"+-- Chars to allow function names to start with, using the 'function' keyword+extendedFunctionStartChars = functionStartChars <|> oneOf "[]*=!" -- Chars to allow in functions using the 'function' keyword-extendedFunctionChars = functionChars <|> oneOf "[]*=!"+extendedFunctionChars = extendedFunctionStartChars <|> oneOf "[]*=!" specialVariable = oneOf (concat specialVariables) paramSubSpecialChars = oneOf "/:+-=%" quotableChars = "|&;<>()\\ '\t\n\r\xA0" ++ doubleQuotableChars@@ -140,15 +147,9 @@ parseProblemAt pos ErrorC 1017 "Literal carriage return. Run script through tr -d '\\r' ." return '\r' -almostSpace =- choice [- check '\xA0' "unicode non-breaking space",- check '\x200B' "unicode zerowidth space"- ]- where- check c name = do- parseNote ErrorC 1018 $ "This is a " ++ name ++ ". Delete and retype it."- char c+almostSpace = do+ parseNote ErrorC 1018 $ "This is a unicode space. Delete and retype it."+ oneOf "\xA0\x2002\x2003\x2004\x2005\x2006\x2007\x2008\x2009\x200B\x202F" return ' ' --------- Message/position annotation on top of user state@@ -160,7 +161,7 @@ deriving (Show) data HereDocContext =- HereDocPending Token [Context] -- on linefeed, read this T_HereDoc+ HereDocPending Id Dashed Quoted String [Context] -- on linefeed, read this T_HereDoc deriving (Show) data UserState = UserState {@@ -168,14 +169,16 @@ positionMap :: Map.Map Id (SourcePos, SourcePos), parseNotes :: [ParseNote], hereDocMap :: Map.Map Id [Token],- pendingHereDocs :: [HereDocContext]+ pendingHereDocs :: [HereDocContext],+ parseShellType :: Shell } initialUserState = UserState { lastId = Id $ -1, positionMap = Map.empty, parseNotes = [], hereDocMap = Map.empty,- pendingHereDocs = []+ pendingHereDocs = [],+ parseShellType = Bash } codeForParseNote (ParseNote _ _ _ code _) = code@@ -238,12 +241,12 @@ hereDocMap = Map.insert id list map } -addPendingHereDoc t = do+addPendingHereDoc id d q str = do state <- getState context <- getCurrentContexts let docs = pendingHereDocs state putState $ state {- pendingHereDocs = HereDocPending t context : docs+ pendingHereDocs = HereDocPending id d q str context : docs } popPendingHereDocs = do@@ -694,8 +697,13 @@ return term readCondNot = do+ notFollowedBy2 $ do+ readEscaped $ string "!"+ spacingOrLf+ choice $ map (try . string) binaryTestOps+ start <- startSpan- char '!'+ if single then void (try (readRegularOrEscaped (string "!"))) else void (char '!') id <- endSpan start spacingOrLf expr <- readCondExpr@@ -826,7 +834,7 @@ char ')' id <- endSpan start spacing- return $ TA_Parentesis id s+ return $ TA_Parenthesis id s readArithTerm = readGroup <|> readVariable <|> readExpansion @@ -946,6 +954,14 @@ prop_readCondition27 = not $ isOk readConditionCommand "[[ x ]] foo" prop_readCondition28 = isOk readCondition "[[ x = [\"$1\"] ]]" prop_readCondition29 = isOk readCondition "[[ x = [*] ]]"+prop_readCondition30 = isOk readCondition "[ \\! \\( -e foo -a -e bar \\) ]"+prop_readCondition31 = isOk readCondition "[ '!' = $x ]"+prop_readCondition32 = isOk readCondition "[ \"!\" = $x ]"+prop_readCondition33 = isOk readCondition "[ \\! = $x ]"+prop_readCondition34 = isWarning readCondition "[ !x = $x ]"+prop_readCondition35 = isWarning readCondition "[ \\!x = $x ]"+prop_readCondition36 = isWarning readCondition "[ '!'x = $x ]"+prop_readCondition37 = isOk readCondition "[ '!' x = $x ]" readCondition = called "test expression" $ do opos <- getPosition@@ -976,7 +992,8 @@ when (open == "[[" && close /= "]]") $ parseProblemAt cpos ErrorC 1033 "Test expression was opened with double [[ but closed with single ]. Make sure they match." when (open == "[" && close /= "]" ) $ parseProblemAt opos ErrorC 1034 "Test expression was opened with single [ but closed with double ]]. Make sure they match." spacing- return $ T_Condition id typ condition+ let closeTyp = if close == "]" then SingleBracket else DoubleBracket+ return $ T_Condition id typ closeTyp condition readAnnotationPrefix = do char '#'@@ -994,6 +1011,21 @@ prop_readAnnotation9 = isOk readAnnotation "# shellcheck source='foo bar' source-path=\"baz etc\"\n" prop_readAnnotation10 = isOk readAnnotation "# shellcheck disable='SC1234,SC2345' enable=\"foo\" shell='bash'\n" prop_readAnnotation11 = isOk (readAnnotationWithoutPrefix False) "external-sources='true'"+prop_readAnnotation12 = isOk readAnnotation "# shellcheck disable=2034-2036\n"+prop_readAnnotation13 = isOk readAnnotation "# shellcheck disable=all,SC2034\n"+prop_readAnnotation14 = isNotOk readAnnotation "# shellcheck disable=foo\n"+prop_readAnnotation15 = isNotOk readAnnotation "# shellcheck disable='foo'\n"+prop_readAnnotation16 = isNotOk readAnnotation "# shellcheck disable=SC2034-x\n"+-- #3425: an invalid disable value should blame the value, not a missing '='+prop_readAnnotationBadDisableMessage =+ "Unknown disable value 'foo'" `isInfixOf` rendered+ && not ("Expected '=' after directive key" `isInfixOf` rendered)+ where+ rendered = case res of+ Left err -> getStringFromParsec $ errorMessages err+ Right _ -> ""+ (res, _) = runIdentity $+ runParser testEnvironment readAnnotation "-" "# shellcheck disable=foo\n" readAnnotation = called "shellcheck directive" $ do try readAnnotationPrefix@@ -1022,7 +1054,19 @@ key <- many1 (letter <|> char '-') char '=' <|> fail "Expected '=' after directive key" annotations <- case key of- "disable" -> plainOrQuoted $ readElement `sepBy` char ','+ "disable" -> do+ pos <- getPosition+ str <- quoted (many1 anyChar)+ <|> many1 (letter <|> digit <|> char '-' <|> char ',')+ <|> return ""+ parsed <- subParse pos+ (try (Just <$> (readElement `sepBy` char ',' <* eof))+ <|> return Nothing)+ str+ case parsed of+ Just annotations -> return annotations+ Nothing -> fail ("Unknown disable value '" ++ str+ ++ "'. Expected a code like 'SC2000', or a range like 'SC2000-SC3000', or 'all'.") where readElement = readRange <|> readAll readAll = do@@ -1057,6 +1101,19 @@ "This shell type is unknown. Use e.g. sh or bash." return [ShellOverride shell] + "extended-analysis" -> do+ pos <- getPosition+ value <- plainOrQuoted $ many1 letter+ case value of+ "true" -> return [ExtendedAnalysis EAAFull]+ "false" -> return [ExtendedAnalysis EAANone]+ "full" -> return [ExtendedAnalysis EAAFull]+ "local" -> return [ExtendedAnalysis EAALocal]+ "none" -> return [ExtendedAnalysis EAANone]+ _ -> do+ parseNoteAt pos ErrorC 1146 "Unknown extended-analysis value. Expected full/local/none (or true/false)."+ return []+ "external-sources" -> do pos <- getPosition value <- plainOrQuoted $ many1 letter@@ -1194,7 +1251,7 @@ readDollarBracedLiteral = do start <- startSpan- vars <- (readBraceEscaped <|> (anyChar >>= \x -> return [x])) `reluctantlyTill1` bracedQuotable+ vars <- (readBraceEscaped <|> ((\x -> [x]) <$> anyChar)) `reluctantlyTill1` bracedQuotable id <- endSpan start return $ T_Literal id $ concat vars @@ -1556,7 +1613,7 @@ return $ concat strings readGenericLiteral1 endExp = do- strings <- (readGenericEscaped <|> (anyChar >>= \x -> return [x])) `reluctantlyTill1` endExp+ strings <- (readGenericEscaped <|> ((\x -> [x]) <$> anyChar)) `reluctantlyTill1` endExp return $ concat strings readGenericEscaped = do@@ -1690,16 +1747,17 @@ prop_readDollarBraceCommandExpansion1 = isOk readDollarBraceCommandExpansion "${ ls; }" prop_readDollarBraceCommandExpansion2 = isOk readDollarBraceCommandExpansion "${\nls\n}"-readDollarBraceCommandExpansion = called "ksh ${ ..; } command expansion" $ do+prop_readDollarBraceCommandExpansion3 = isOk readDollarBraceCommandExpansion "${| REPLY=42; }"+readDollarBraceCommandExpansion = called "ksh-style ${ ..; } command expansion" $ do start <- startSpan- try $ do- string "${"- whitespace+ c <- try $ do+ string "${"+ char '|' <|> whitespace allspacing term <- readTerm- char '}' <|> fail "Expected } to end the ksh ${ ..; } command expansion"+ char '}' <|> fail "Expected } to end the ksh-style ${ ..; } command expansion" id <- endSpan start- return $ T_DollarBraceCommandExpansion id term+ return $ T_DollarBraceCommandExpansion id (if c == '|' then Piped else Unpiped) term prop_readDollarBraced1 = isOk readDollarBraced "${foo//bar/baz}" prop_readDollarBraced2 = isOk readDollarBraced "${foo/'{cow}'}"@@ -1835,7 +1893,7 @@ -- add empty tokens for now, read the rest in readPendingHereDocs let doc = T_HereDoc hid dashed quoted endToken []- addPendingHereDoc doc+ addPendingHereDoc hid dashed quoted endToken return doc where unquote :: String -> (Quoted, String)@@ -1856,7 +1914,7 @@ docs <- popPendingHereDocs mapM_ readDoc docs where- readDoc (HereDocPending (T_HereDoc id dashed quoted endToken _) ctx) =+ readDoc (HereDocPending id dashed quoted endToken ctx) = swapContext ctx $ do docStartPos <- getPosition@@ -2049,6 +2107,8 @@ "Unexpected start of line. If breaking lines, |/||/&& should be at the end of the previous one." readLineBreak = optional readNewlineList +data BackgroundOperator = Ampersand | Coprocess+ prop_readSeparator1 = isWarning readScript "a &; b" prop_readSeparator2 = isOk readScript "a & b" prop_readSeparator3 = isWarning readScript "a & b"@@ -2058,7 +2118,7 @@ notFollowedBy2 (void g_AND_IF <|> void readCaseSeparator) notFollowedBy2 (string "&>") start <- getPosition- f <- try (do+ f <- (Just Coprocess <$ readKshCoprocessOp) <|> try (do pos <- getPosition char '&' optional $ choice [@@ -2078,12 +2138,18 @@ -- In case statements we might have foo & ;; notFollowedBy2 $ char ';' parseProblemAt pos ErrorC 1045 "It's not 'foo &; bar', just 'foo & bar'."- return '&'- ) <|> char ';' <|> char '&'+ return $ Just Ampersand+ ) <|> (Nothing <$ char ';') <|> (Just Ampersand <$ char '&') end <- getPosition spacing return (f, (start, end)) +-- In Ksh, |& terminates the preceding and-or list, like &.+readKshCoprocessOp = do+ shell <- parseShellType <$> getState+ guard $ shell == Ksh+ void $ try $ string "|&"+ readSequentialSep = void (g_Semi >> readLineBreak) <|> void readNewlineList readSeparator = do@@ -2095,7 +2161,7 @@ start <- getPosition readNewlineList end <- getPosition- return ('\n', (start, end))+ return (Nothing, (start, end)) prop_readSimpleCommand = isOk readSimpleCommand "echo test > file" prop_readSimpleCommand2 = isOk readSimpleCommand "cmd &> file"@@ -2113,6 +2179,10 @@ prop_readSimpleCommand13 = isWarning readSimpleCommand "ElseIf foo" prop_readSimpleCommand14 = isWarning readSimpleCommand "elseif[$i==2]" prop_readSimpleCommand15 = isWarning readSimpleCommand "trap 'foo\"bar' INT"+prop_readSimpleCommand16 = isOk readSimpleCommand "builtin export foo=(bar baz)"+prop_readSimpleCommand17 = isOk readSimpleCommand "builtin declare -a foo=(bar baz)"+prop_readSimpleCommand18 = isNotOk readSimpleCommand "builtin echo foo=(bar baz)"+prop_readSimpleCommand19 = isNotOk readSimpleCommand "echo export foo=(bar baz)" readSimpleCommand = called "simple command" $ do prefix <- option [] readCmdPrefix skipAnnotationAndWarn@@ -2128,10 +2198,13 @@ Just cmd -> do validateCommand cmd -- We have to ignore possible parsing problems from the lookAhead parser- firstArgument <- ignoreProblemsOf . optionMaybe . try . lookAhead $ readCmdWord+ -- Only look ahead after `builtin`: parsing every first argument twice doubles the work per nested $(..)+ firstArgument <- if isCommand ["builtin"] cmd+ then ignoreProblemsOf . optionMaybe . try . lookAhead $ readCmdWord+ else return Nothing suffix <- option [] $ getParser readCmdSuffix -- If `export` or other modifier commands are called with `builtin` we have to look at the first argument- (if isCommand ["builtin"] cmd then fromMaybe cmd firstArgument else cmd) [+ (fromMaybe cmd firstArgument) [ (["declare", "export", "local", "readonly", "typeset"], readModifierSuffix), (["time"], readTimeSuffix), (["let"], readLetSuffix),@@ -2200,17 +2273,18 @@ readSource :: Monad m => Token -> SCParser m Token-readSource t@(T_Redirecting _ _ (T_SimpleCommand cmdId _ (cmd:file':rest'))) = do- let file = getFile file' rest'+readSource t@(T_Redirecting _ _ (T_SimpleCommand cmdId _ (cmd:args'))) = do+ let file = getFile args' override <- getSourceOverride let literalFile = do- name <- override `mplus` getLiteralString file `mplus` stripDynamicPrefix file+ name <- override `mplus` (getLiteralString =<< file) `mplus` (stripDynamicPrefix =<< file) -- Hack to avoid 'source ~/foo' trying to read from literal tilde guard . not $ "~/" `isPrefixOf` name return name+ let fileId = fromMaybe (getId cmd) (getId <$> file) case literalFile of Nothing -> do- parseNoteAtId (getId file) WarningC 1090+ parseNoteAtId fileId WarningC 1090 "ShellCheck can't follow non-constant source. Use a directive to specify location." return t Just filename -> do@@ -2218,7 +2292,7 @@ if not proceed then do -- FIXME: This actually gets squashed without -a- parseNoteAtId (getId file) InfoC 1093+ parseNoteAtId fileId InfoC 1093 "This file appears to be recursively sourced. Ignoring." return t else do@@ -2236,7 +2310,7 @@ return (contents, resolved) case input of Left err -> do- parseNoteAtId (getId file) InfoC 1091 $+ parseNoteAtId fileId InfoC 1091 $ "Not following: " ++ err return t Right script -> do@@ -2248,18 +2322,19 @@ return $ T_SourceCommand id1 t (T_Include id2 src) let failed = do- parseNoteAtId (getId file) WarningC 1094+ parseNoteAtId fileId WarningC 1094 "Parsing of sourced file failed. Ignoring it." return t included <|> failed where- getFile :: Token -> [Token] -> Token- getFile file (next:rest) =- case getLiteralString file of- Just "--" -> next- x -> file- getFile file _ = file+ getFile :: [Token] -> Maybe Token+ getFile (first:rest) =+ case getLiteralString first of+ Just "--" -> rest !!! 0+ Just "-p" -> rest !!! 1+ _ -> return first+ getFile _ = Nothing getSourcePath t = case t of@@ -2283,23 +2358,32 @@ subRead name script = withContext (ContextSource name) $- inSeparateContext $- subParse (initialPos name) (readScriptFile True) script+ inSeparateContext $ do+ oldState <- getState+ setState $ oldState { pendingHereDocs = [] }+ result <- subParse (initialPos name) (readScriptFile True) script+ newState <- getState+ setState $ newState { pendingHereDocs = pendingHereDocs oldState }+ return result readSource t = return t prop_readPipeline = isOk readPipeline "! cat /etc/issue | grep -i ubuntu" prop_readPipeline2 = isWarning readPipeline "!cat /etc/issue | grep -i ubuntu" prop_readPipeline3 = isOk readPipeline "for f; do :; done|cat"+prop_readPipeline4 = isOk readPipeline "! ! true"+prop_readPipeline5 = isOk readPipeline "true | ! true" readPipeline = do unexpecting "keyword/token" readKeyword- do- (T_Bang id) <- g_Bang- pipe <- readPipeSequence- return $ T_Banged id pipe- <|>- readPipeSequence+ readBanged readPipeSequence +readBanged parser = do+ pos <- getPosition+ (T_Bang id) <- g_Bang+ next <- readBanged parser+ return $ T_Banged id next+ <|> parser+ prop_readAndOr = isOk readAndOr "grep -i lol foo || exit 1" prop_readAndOr1 = isOk readAndOr "# shellcheck disable=1\nfoo" prop_readAndOr2 = isOk readAndOr "# shellcheck disable=1\n# lol\n# shellcheck disable=3\nfoo"@@ -2331,6 +2415,14 @@ return [] prop_readTerm = isOk readTerm "time ( foo; bar; )"+prop_readKshCoprocessAndOr =+ case debugParse readScript "#!/bin/ksh\ntrue && echo data |& read -r -p record" of+ Right (T_Annotation _ _ (T_Script _ _ [T_KshCoprocess _ (T_AndIf _ _ _), _])) -> True+ _ -> False++prop_readKshCoprocessBeforeClosingDelimiter =+ isOk readScript "#!/bin/ksh\n{ true|& }"+ readTerm = do allspacing m <- readAndOr@@ -2348,20 +2440,21 @@ <|> return [current] where- transformWithSeparator i '&' = T_Backgrounded i- transformWithSeparator i _ = id+ transformWithSeparator i (Just Ampersand) = T_Backgrounded i+ transformWithSeparator i (Just Coprocess) = T_KshCoprocess i+ transformWithSeparator _ Nothing = id readPipeSequence = do start <- startSpan- (cmds, pipes) <- sepBy1WithSeparators readCommand+ (cmds, pipes) <- sepBy1WithSeparators (readBanged readCommand) (readPipe `thenSkip` (spacing >> readLineBreak)) id <- endSpan start spacing return $ T_Pipeline id pipes cmds where sepBy1WithSeparators p s = do- let elems = p >>= \x -> return ([x], [])+ let elems = (\x -> ([x], [])) <$> p let seps = do separator <- s return $ \(a,b) (c,d) -> (a++c, b ++ d ++ [separator])@@ -2369,6 +2462,7 @@ readPipe = do notFollowedBy2 g_OR_IF+ notFollowedBy2 readKshCoprocessOp start <- startSpan char '|' qualifier <- string "&" <|> return ""@@ -2384,6 +2478,10 @@ ] readCmdName = do+ -- If the command name is `!` then+ optional . lookAhead . try $ do+ char '!'+ whitespace -- Ignore alias suppression optional . try $ do char '\\'@@ -2733,6 +2831,8 @@ prop_readFunctionDefinition11 = isWarning readFunctionDefinition "function foo{\ntrue\n}" prop_readFunctionDefinition12 = isOk readFunctionDefinition "function []!() { true; }" prop_readFunctionDefinition13 = isOk readFunctionDefinition "@require(){ true; }"+prop_readFunctionDefinition14 = isOk readFunctionDefinition "foo#bar(){ :; }"+prop_readFunctionDefinition15 = isNotOk readFunctionDefinition "#bar(){ :; }" readFunctionDefinition = called "function" $ do start <- startSpan functionSignature <- try readFunctionSignature@@ -2750,7 +2850,7 @@ string "function" whitespace spacing- name <- many1 extendedFunctionChars+ name <- (:) <$> extendedFunctionStartChars <*> many extendedFunctionChars spaces <- spacing hasParens <- wasIncluded readParens when (not hasParens && null spaces) $@@ -2759,7 +2859,7 @@ return $ \id -> T_Function id (FunctionKeyword True) (FunctionParentheses hasParens) name readWithoutFunction = try $ do- name <- many1 functionChars+ name <- (:) <$> functionStartChars <*> many functionChars guard $ name /= "time" -- Interferes with time ( foo ) spacing readParens@@ -2777,17 +2877,29 @@ prop_readCoProc1 = isOk readCoProc "coproc foo { echo bar; }" prop_readCoProc2 = isOk readCoProc "coproc { echo bar; }" prop_readCoProc3 = isOk readCoProc "coproc echo bar"+prop_readCoProc4 = isOk readCoProc "coproc a=b echo bar"+prop_readCoProc5 = isOk readCoProc "coproc 'foo' { echo bar; }"+prop_readCoProc6 = isOk readCoProc "coproc \"foo$$\" { echo bar; }"+prop_readCoProc7 = isOk readCoProc "coproc 'foo' ( echo bar )"+prop_readCoProc8 = isOk readCoProc "coproc \"foo$$\" while true; do true; done" readCoProc = called "coproc" $ do start <- startSpan try $ do string "coproc"- whitespace+ spacing1 choice [ try $ readCompoundCoProc start, readSimpleCoProc start ] where readCompoundCoProc start = do- var <- optionMaybe $- readVariableName `thenSkip` whitespace- body <- readBody readCompoundCommand+ notFollowedBy2 readAssignmentWord+ (var, body) <- choice [+ try $ do+ body <- readBody readCompoundCommand+ return (Nothing, body),+ try $ do+ var <- readNormalWord `thenSkip` spacing+ body <- readBody readCompoundCommand+ return (Just var, body)+ ] id <- endSpan start return $ T_CoProc id var body readSimpleCoProc start = do@@ -2891,8 +3003,8 @@ kludgeAwayQuotes :: String -> SourcePos -> (String, SourcePos) kludgeAwayQuotes s p = case s of- first:rest@(_:_) ->- let (last:backwards) = reverse rest+ first:second:rest ->+ let (last NE.:| backwards) = NE.reverse (second NE.:| rest) middle = reverse backwards in if first `elem` "'\"" && first == last@@ -3152,9 +3264,14 @@ prop_readShebang5 = isWarning readShebang "\n#!/bin/sh" prop_readShebang6 = isWarning readShebang " # Copyright \n!#/bin/bash" prop_readShebang7 = isNotOk readShebang "# Copyright \nfoo\n#!/bin/bash"+prop_readShebang8 = isWarning readShebang "# !/bin/bash\n"+prop_readShebang9 = isNotOk readShebang "# ! Grave\n"+prop_readShebang10 = isWarning readShebang "# Copyright\n# ! /bin/bash\n"+prop_readShebang11 = isNotOk readShebang "# Some of the accent codes:\n# ! Grave\n"+prop_readShebang12 = isWarning readShebang "# Some of the accent codes:\n# ! Grave\n#!/bin/bash\n" readShebang = do start <- startSpan- anyShebang <|> try readMissingBang <|> withHeader+ anyShebang <|> try readMissingBang <|> try withHeader many linewhitespace str <- many $ noneOf "\r\n" id <- endSpan start@@ -3185,6 +3302,8 @@ middlePos <- getPosition middleSpaces <- skipSpaces char '!'+ -- Don't consider a comment like "# ! Note" a shebang unless a path follows+ when middleSpaces $ void ensurePathAhead when startSpaces $ parseProblemAt startPos ErrorC 1114 "Remove leading spaces before the shebang."@@ -3205,6 +3324,8 @@ ensurePathAhead parseProblemAt pos ErrorC 1113 "Use #!, not just #, for the shebang."+ -- Emit a warning, but don't consider a leading comment a valid shebang+ fail "" ensurePathAhead = lookAhead $ do many linewhitespace@@ -3250,13 +3371,18 @@ Just (file, str) -> readConfig file str readConfig filename contents = do- result <- lift $ runParserT readConfigKVs initialUserState filename contents+ result <- lift $+ runParserT (parseWithNotes readConfigKVs) initialUserState filename contents case result of- Right result ->- return result+ Right (annotations, userState) -> do+ mapM_ addParseNote (parseNotes userState)+ return annotations Left err -> do- parseProblem ErrorC 1134 $ errorFor filename err+ -- Report the error at its location in the config file+ -- (e.g. .shellcheckrc or .editorconfig), not at the+ -- current position in the script being checked.+ parseProblemAt (errorPos err) ErrorC 1134 $ errorFor filename err return [] errorFor filename err =@@ -3313,19 +3439,27 @@ annotationId <- endSpan annotationStart let shellAnnotationSpecified = any (\x -> case x of ShellOverride {} -> True; _ -> False) annotations- shellFlagSpecified <- isJust <$> Mr.asks shellTypeOverride- let ignoreShebang = shellAnnotationSpecified || shellFlagSpecified+ shellOverride <- Mr.asks shellTypeOverride+ let ignoreShebang = shellAnnotationSpecified || isJust shellOverride+ let executable = executableFromShebang shebangString unless ignoreShebang $- verifyShebang pos (executableFromShebang shebangString)- if ignoreShebang || isValidShell (executableFromShebang shebangString) /= Just False+ verifyShebang pos executable+ if ignoreShebang || isValidShell executable /= Just False then do+ unless sourced $ do+ filename <- Mr.asks currentFilename+ let dialect = fromMaybe Bash $ msum+ [shellOverride, shellFromAnnotations annotations executable, shellFromFilename filename]+ modifyState $ \state -> state { parseShellType = dialect } commands <- readCompoundListOrEmpty id <- endSpan start+ readPendingHereDocs verifyEof let script = T_Annotation annotationId annotations $ T_Script id shebang commands- reparseIndices script+ userstate <- getState+ reparseIndices $ reattachHereDocs script (hereDocMap userstate) else do many anyChar id <- endSpan start@@ -3335,8 +3469,8 @@ verifyShebang pos s = do case isValidShell s of Just True -> return ()- Just False -> parseProblemAt pos ErrorC 1071 "ShellCheck only supports sh/bash/dash/ksh scripts. Sorry!"- Nothing -> parseProblemAt pos ErrorC 1008 "This shebang was unrecognized. ShellCheck only supports sh/bash/dash/ksh. Add a 'shell' directive to specify."+ Just False -> parseProblemAt pos ErrorC 1071 "ShellCheck only supports sh/bash/dash/ksh/'busybox sh' scripts. Sorry!"+ Nothing -> parseProblemAt pos ErrorC 1008 "This shebang was unrecognized. ShellCheck only supports sh/bash/dash/ksh/'busybox sh'. Add a 'shell' directive to specify." isValidShell s = let good = null s || any (`isPrefixOf` s) goodShells@@ -3352,16 +3486,20 @@ "sh", "ash", "dash",+ "busybox sh", "bash", "bats",- "ksh"+ "ksh",+ "oksh" ] badShells = [ "awk", "csh", "expect",+ "fish", "perl", "python",+ "python3", "ruby", "tcsh", "zsh"@@ -3414,14 +3552,23 @@ isWarning p s = parsesCleanly p s == Just False -- The string parses with warnings isNotOk p s = parsesCleanly p s == Nothing -- The string does not parse -parsesCleanly parser string = runIdentity $ do- (res, sys) <- runParser testEnvironment- (parser >> eof >> getState) "-" string- case (res, sys) of- (Right userState, systemState) ->- return $ Just . null $ parseNotes userState ++ parseProblems systemState- (Left _, _) -> return Nothing+-- If the parser matches the string, return Right [ParseNotes+ParseProblems]+-- If it does not match the string, return Left [ParseProblems]+getParseOutput parser string = runIdentity $ do+ (res, systemState) <- runParser testEnvironment+ (parser >> eof >> getState) "-" string+ return $ case res of+ Right userState ->+ Right $ parseNotes userState ++ parseProblems systemState+ Left _ -> Left $ parseProblems systemState +-- If the parser matches the string, return Just whether it was clean (without emitting suggestions)+-- Otherwise, Nothing+parsesCleanly parser string =+ case getParseOutput parser string of+ Right list -> Just $ null list+ Left _ -> Nothing+ parseWithNotes parser = do item <- parser state <- getState@@ -3438,9 +3585,8 @@ pos = errorPos parsecError getStringFromParsec errors =- case map f errors of- r -> unwords (take 1 $ catMaybes $ reverse r) ++- " Fix any mentioned problems and try again."+ headOrDefault "" (mapMaybe f $ reverse errors) +++ " Fix any mentioned problems and try again." where f err = case err of@@ -3467,12 +3613,12 @@ parseShell env name contents = do (result, state) <- runParser env (parseWithNotes readScript) name contents case result of- Right (script, userstate) ->+ Right (script, userstate) -> do+ let isScriptLevelDisabled c = isAnnotationIgnoringCode (codeForParseNote c) script return newParseResult {- prComments = map toPositionedComment $ nub $ parseNotes userstate ++ parseProblems state,+ prComments = map toPositionedComment $ filter (not . isScriptLevelDisabled) $ nub $ parseNotes userstate ++ parseProblems state, prTokenPositions = Map.map startEndPosToPos (positionMap userstate),- prRoot = Just $- reattachHereDocs script (hereDocMap userstate)+ prRoot = Just script } Left err -> do let context = contextStack state@@ -3490,13 +3636,11 @@ -- A final pass for ignoring parse errors after failed parsing isIgnored stack note = any (contextItemDisablesCode False (codeForParseNote note)) stack -notesForContext list = zipWith ($) [first, second] $ filter isName list+notesForContext list = zipWith ($) [first, second] [(pos, str) | ContextName pos str <- list] where- isName (ContextName _ _) = True- isName _ = False- first (ContextName pos str) = ParseNote pos pos ErrorC 1073 $+ first (pos, str) = ParseNote pos pos ErrorC 1073 $ "Couldn't parse this " ++ str ++ ". Fix to allow more checks."- second (ContextName pos str) = ParseNote pos pos InfoC 1009 $+ second (pos, str) = ParseNote pos pos InfoC 1009 $ "The mentioned syntax error was in this " ++ str ++ "." -- Go over all T_UnparsedIndex and reparse them as either arithmetic or text
striptests view
@@ -40,7 +40,7 @@ # Delete tests /^prop_/ { state = 1; next; } - # ..and any blank lines following them.+ # ..and any indented lines following them. state == 1 && /^ / { next; } # Template Haskell marker@@ -60,7 +60,7 @@ exit 1 fi -if [[ -d '.git' ]] && ! git diff --exit-code > /dev/null 2>&1+if [[ -d '.git' ]] && git --version > /dev/null && ! git diff --exit-code > /dev/null 2>&1 then echo "You have local changes! These may be overwritten." >&2 exit 2
test/shellcheck.hs view
@@ -12,27 +12,32 @@ import qualified ShellCheck.Checks.ControlFlow import qualified ShellCheck.Checks.Custom import qualified ShellCheck.Checks.ShellSupport+import qualified ShellCheck.EditorConfig import qualified ShellCheck.Fixer import qualified ShellCheck.Formatter.Diff import qualified ShellCheck.Parser main = do putStrLn "Running ShellCheck tests..."- results <- sequence [- ShellCheck.Analytics.runTests- ,ShellCheck.AnalyzerLib.runTests- ,ShellCheck.ASTLib.runTests- ,ShellCheck.CFG.runTests- ,ShellCheck.CFGAnalysis.runTests- ,ShellCheck.Checker.runTests- ,ShellCheck.Checks.Commands.runTests- ,ShellCheck.Checks.ControlFlow.runTests- ,ShellCheck.Checks.Custom.runTests- ,ShellCheck.Checks.ShellSupport.runTests- ,ShellCheck.Fixer.runTests- ,ShellCheck.Formatter.Diff.runTests- ,ShellCheck.Parser.runTests+ failures <- filter (not . snd) <$> mapM sequenceA tests+ if null failures then exitSuccess else do+ putStrLn "Tests failed for the following module(s):"+ mapM (putStrLn . ("- ShellCheck." ++) . fst) failures+ exitFailure+ where+ tests =+ [ ("Analytics" , ShellCheck.Analytics.runTests)+ , ("AnalyzerLib" , ShellCheck.AnalyzerLib.runTests)+ , ("ASTLib" , ShellCheck.ASTLib.runTests)+ , ("CFG" , ShellCheck.CFG.runTests)+ , ("CFGAnalysis" , ShellCheck.CFGAnalysis.runTests)+ , ("Checker" , ShellCheck.Checker.runTests)+ , ("Checks.Commands" , ShellCheck.Checks.Commands.runTests)+ , ("Checks.ControlFlow" , ShellCheck.Checks.ControlFlow.runTests)+ , ("Checks.Custom" , ShellCheck.Checks.Custom.runTests)+ , ("Checks.ShellSupport", ShellCheck.Checks.ShellSupport.runTests)+ , ("EditorConfig" , ShellCheck.EditorConfig.runTests)+ , ("Fixer" , ShellCheck.Fixer.runTests)+ , ("Formatter.Diff" , ShellCheck.Formatter.Diff.runTests)+ , ("Parser" , ShellCheck.Parser.runTests) ]- if and results- then exitSuccess- else exitFailure