packages feed

ShellCheck 0.11.0 → 0.12.0

raw patch · 24 files changed

+2263/−519 lines, 24 filesdep −processdep ~Diffdep ~QuickCheckdep ~aesonnew-component:exe:shellcheck-devPVP ok

version bump matches the API change (PVP)

Dependencies removed: process

Dependency ranges changed: Diff, QuickCheck, aeson, base, containers, deepseq, directory, fgl

API changes (from Hackage documentation)

- ShellCheck.AnalyzerLib: [hasSetE] :: Parameters -> Bool
- ShellCheck.AnalyzerLib: containsSetE :: Token -> Bool
- ShellCheck.AnalyzerLib: containsSetOption :: [Char] -> Token -> Bool
- ShellCheck.AnalyzerLib: containsShopt :: [Char] -> Token -> Bool
+ ShellCheck.AST: EAAFull :: ExtendedAnalysisAnnotation
+ ShellCheck.AST: EAALocal :: ExtendedAnalysisAnnotation
+ ShellCheck.AST: EAANone :: ExtendedAnalysisAnnotation
+ ShellCheck.AST: Inner_T_KshCoprocess :: t -> InnerToken t
+ ShellCheck.AST: data ExtendedAnalysisAnnotation
+ ShellCheck.AST: instance GHC.Classes.Eq ShellCheck.AST.ExtendedAnalysisAnnotation
+ ShellCheck.AST: instance GHC.Show.Show ShellCheck.AST.ExtendedAnalysisAnnotation
+ ShellCheck.AST: pattern T_KshCoprocess :: Id -> Token -> Token
+ ShellCheck.ASTLib: prop_getLiteralString14 :: Bool
+ ShellCheck.ASTLib: prop_getLiteralString15 :: Bool
+ ShellCheck.ASTLib: prop_getLiteralString16 :: Bool
+ ShellCheck.ASTLib: prop_getLiteralString17 :: Bool
+ ShellCheck.ASTLib: prop_getLiteralString18 :: Bool
+ ShellCheck.ASTLib: prop_getLiteralString19 :: Bool
+ ShellCheck.ASTLib: prop_getLiteralString20 :: Bool
+ ShellCheck.ASTLib: prop_getLiteralString21 :: Bool
+ ShellCheck.ASTLib: prop_getLiteralString22 :: Bool
+ ShellCheck.ASTLib: prop_getLiteralString23 :: Bool
+ ShellCheck.AnalyzerLib: FunctionScope :: Scope
+ ShellCheck.AnalyzerLib: [hasAllexport] :: Parameters -> Bool
+ ShellCheck.AnalyzerLib: [hasErrexit] :: Parameters -> Bool
+ ShellCheck.AnalyzerLib: [hasNoglob] :: Parameters -> Bool
+ ShellCheck.AnalyzerLib: containsAllexport :: Token -> Bool
+ ShellCheck.AnalyzerLib: containsErrexit :: Token -> Bool
+ ShellCheck.AnalyzerLib: containsExecfail :: Token -> Bool
+ ShellCheck.AnalyzerLib: containsInheritErrexit :: Token -> Bool
+ ShellCheck.AnalyzerLib: containsLastpipe :: Token -> Bool
+ ShellCheck.AnalyzerLib: containsNoglob :: Token -> Bool
+ ShellCheck.AnalyzerLib: containsPipefail :: Token -> Bool
+ ShellCheck.AnalyzerLib: containsPosix :: Token -> Bool
+ ShellCheck.AnalyzerLib: extendedAnalysisAnnotationToMode :: ExtendedAnalysisAnnotation -> ExtendedAnalysisMode
+ ShellCheck.AnalyzerLib: getBatsRunVariables :: [Token] -> [(String, DataType)]
+ ShellCheck.AnalyzerLib: isCondition :: NonEmpty Token -> Bool
+ ShellCheck.AnalyzerLib: prop_supportedShellsResolve :: Bool
+ ShellCheck.AnalyzerLib: runAndGetCodes :: Checker -> String -> Maybe [Integer]
+ ShellCheck.CFG: CFVPReadonly :: CFVariableProp
+ ShellCheck.CFG: [cfSourceAsBoundary] :: CFGParameters -> Bool
+ ShellCheck.CFGAnalysis: [cfSourceAsBoundary] :: CFGParameters -> Bool
+ ShellCheck.CFGAnalysis: variableMustBeDeclaredReadonly :: ProgramState -> String -> Maybe Bool
+ ShellCheck.Data: privilegeElevationCommands :: [String]
+ ShellCheck.Data: shellFromAnnotations :: [Annotation] -> String -> Maybe Shell
+ ShellCheck.Data: shellFromFilename :: String -> Maybe Shell
+ ShellCheck.Data: supportedShellDialects :: [String]
+ ShellCheck.EditorConfig: editorConfigDirectives :: String -> FilePath -> Maybe String
+ ShellCheck.EditorConfig: globToRegexString :: String -> String
+ ShellCheck.EditorConfig: invalidDirectiveLines :: String -> FilePath -> [Int]
+ ShellCheck.EditorConfig: invalidRootLines :: String -> [Int]
+ ShellCheck.EditorConfig: isEditorConfigRoot :: String -> Bool
+ ShellCheck.EditorConfig: parseEditorConfig :: String -> FilePath -> String
+ ShellCheck.EditorConfig: runTests :: IO Bool
+ ShellCheck.Formatter.TTY: wikiLink :: String
+ ShellCheck.Interface: ExtendedAnalysisFull :: ExtendedAnalysisMode
+ ShellCheck.Interface: ExtendedAnalysisLocal :: ExtendedAnalysisMode
+ ShellCheck.Interface: ExtendedAnalysisNone :: ExtendedAnalysisMode
+ ShellCheck.Interface: data ExtendedAnalysisMode
+ ShellCheck.Interface: instance GHC.Classes.Eq ShellCheck.Interface.ExtendedAnalysisMode
+ ShellCheck.Interface: instance GHC.Classes.Ord ShellCheck.Interface.ExtendedAnalysisMode
+ ShellCheck.Interface: instance GHC.Show.Show ShellCheck.Interface.ExtendedAnalysisMode
- ShellCheck.AST: ExtendedAnalysis :: Bool -> Annotation
+ ShellCheck.AST: ExtendedAnalysis :: ExtendedAnalysisAnnotation -> Annotation
- ShellCheck.AST: Inner_T_Condition :: ConditionType -> t -> InnerToken t
+ ShellCheck.AST: Inner_T_Condition :: ConditionType -> ConditionType -> t -> InnerToken t
- ShellCheck.AST: pattern T_Condition :: Id -> ConditionType -> Token -> Token
+ ShellCheck.AST: pattern T_Condition :: Id -> ConditionType -> ConditionType -> Token -> Token
- ShellCheck.ASTLib: getExtendedAnalysisDirective :: Token -> Maybe Bool
+ ShellCheck.ASTLib: getExtendedAnalysisDirective :: Token -> Maybe ExtendedAnalysisAnnotation
- ShellCheck.AnalyzerLib: Parameters :: Bool -> Bool -> Bool -> Bool -> Bool -> [StackData] -> Map Id Token -> Map Id Token -> Shell -> Bool -> Token -> Map Id (Position, Position) -> Maybe CFGAnalysis -> Parameters
+ ShellCheck.AnalyzerLib: Parameters :: Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> [StackData] -> Map Id Token -> Map Id Token -> Shell -> Bool -> Token -> Map Id (Position, Position) -> Maybe CFGAnalysis -> Parameters
- ShellCheck.AnalyzerLib: isOptionSet :: [Char] -> Token -> Bool
+ ShellCheck.AnalyzerLib: isOptionSet :: [Char] -> Maybe Char -> Token -> Bool
- ShellCheck.CFG: CFGParameters :: Bool -> Bool -> CFGParameters
+ ShellCheck.CFG: CFGParameters :: Bool -> Bool -> Bool -> CFGParameters
- ShellCheck.CFGAnalysis: CFGParameters :: Bool -> Bool -> CFGParameters
+ ShellCheck.CFGAnalysis: CFGParameters :: Bool -> Bool -> Bool -> CFGParameters

Files

CHANGELOG.md view
@@ -1,3 +1,47 @@+## 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.
README.md view
@@ -225,6 +225,11 @@  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@@ -240,6 +245,7 @@ * [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)@@ -247,9 +253,6 @@ or see the [GitHub Releases](https://github.com/koalaman/shellcheck/releases) for other releases (including the [latest](https://github.com/koalaman/shellcheck/releases/tag/latest) meta-release for daily git builds). -There are currently no official binaries for Apple Silicon, but third party builds are available via-[ShellCheck for Visual Studio Code](https://github.com/vscode-shellcheck/shellcheck-binaries/releases).- Distro packages already come with a `man` page. If you are building from source, it can be installed with:  ```console@@ -264,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@@ -406,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@@ -445,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@@ -518,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 ``` 
ShellCheck.cabal view
@@ -1,5 +1,5 @@ Name:             ShellCheck-Version:          0.11.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.12.1-      aeson                >= 1.4.0 && < 2.3,+      -- 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.13,       containers           >= 0.5.6 && < 0.9,-      deepseq              >= 1.4.1 && < 1.6,-      Diff                 >= 0.4.0 && < 1.1,-      fgl                  (>= 5.7.0 && < 5.8.1.0) || (>= 5.8.1.1 && < 5.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.17,+      QuickCheck           >= 2.14.2 && < 2.20,       regex-tdfa           >= 1.2.0 && < 1.4,       transformers         >= 0.4.2 && < 0.7, -      -- getXdgDirectory from 1.2.3.0-      directory            >= 1.2.3 && < 1.4,--      -- 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,19 +56,28 @@     options are cumulative, but all the codes can be specified at once,     comma-separated as a single argument. -**--extended-analysis=true/false**+**--extended-analysis=full/local/none** -:   Enable/disable Dataflow Analysis to identify more issues (default true). If+:   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 disabled with this flag-    or a directive. This flag overrides directives and rc files.+    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**@@ -76,12 +85,14 @@  **--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.+    in the default locations. The specified file is not read if+    **--norc** is also given.  **-o**\ *NAME1*[,*NAME2*...],\ **--enable=***NAME1*[,*NAME2*...] @@ -92,7 +103,7 @@ **-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*@@ -116,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** @@ -132,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**@@ -147,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** @@ -184,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@@ -196,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@@ -215,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.@@ -249,7 +272,9 @@ :   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**@@ -257,11 +282,16 @@     Only file-wide `enable` directives are considered.  **extended-analysis**-:   Set to true/false to enable/disable dataflow analysis. Specifying-    `# shellcheck extended-analysis=false` in particularly large (2000+ line)+:   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. Extended analysis is enabled by default.+    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).@@ -286,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 @@ -317,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_HOME`-(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:@@ -397,7 +456,7 @@  # COPYRIGHT -Copyright 2012-2025, 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 
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 @@ -103,14 +104,14 @@     Option "e" ["exclude"]         (ReqArg (Flag "exclude") "CODE1,CODE2..") "Exclude types of warnings",     Option "" ["extended-analysis"]-        (ReqArg (Flag "extended-analysis") "bool") "Perform dataflow analysis (default true)",+        (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",@@ -121,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, busybox)",+        (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)",@@ -134,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@@ -208,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@@ -253,11 +298,20 @@             }             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 lookup value list of         Just value -> return value@@ -285,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) {@@ -379,15 +434,23 @@                 rcfile = Just str             } -        Flag "enable" value ->-            let cs = checkSpec options in return options {+        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 <- parseBool str+            value <- parseExtendedAnalysis str             return options {                 checkSpec = (checkSpec options) {                     csExtendedAnalysis = Just value@@ -397,6 +460,9 @@         -- 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@@ -419,8 +485,21 @@                 printErr $ "Invalid boolean, expected true/false: " ++ str                 throwError SyntaxFailure -ioInterface :: Options -> [FilePath] -> IO (SystemInterface IO)-ioInterface options files = do+    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)@@ -470,8 +549,29 @@         fallback path _ = return path  -    -- Returns the name and contents of .shellcheckrc for the given file-    getConfig cache filename =+    -- 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+        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.@@ -479,9 +579,10 @@                 if path == "/"                   then return result                   else do-                    result <- readConfig file-                    when (isNothing result) $+                    result <- readConfig doesFileExist onRcReadFailure file+                    when (isNothing result) $ do                         hPutStrLn stderr $ "Warning: unable to read --rcfile " ++ file+                        onRcReadFailure                     writeIORef cache ("/", result)                     return result @@ -497,15 +598,85 @@                     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.@@ -522,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@@ -534,6 +705,7 @@         handler :: FilePath -> IOException -> IO (String, Bool)         handler file err = do             hPutStrLn stderr $ file ++ ": " ++ show err+            onReadFailure             return ("", True)      andM a b arg = do@@ -629,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
@@ -65,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@@ -73,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@@ -153,8 +154,12 @@     | ShellOverride String     | SourcePath String     | ExternalSources Bool-    | ExtendedAnalysis 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@@ -213,6 +218,7 @@ 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)@@ -223,7 +229,7 @@ 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)@@ -260,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_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_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
@@ -33,7 +33,7 @@ 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 @@ -386,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.@@ -409,37 +419,34 @@             '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 [] = [] @@ -916,7 +923,7 @@         T_Annotation _ list _ -> [s | EnableComment s <- list]         _ -> [] -getExtendedAnalysisDirective :: Token -> Maybe Bool+getExtendedAnalysisDirective :: Token -> Maybe ExtendedAnalysisAnnotation getExtendedAnalysisDirective root =     case root of         T_Annotation _ list _ -> listToMaybe $ [s | ExtendedAnalysis s <- list]
src/ShellCheck/Analytics.hs view
@@ -20,6 +20,7 @@ {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE PatternGuards #-}+{-# LANGUAGE NondecreasingIndentation #-} module ShellCheck.Analytics (checker, optionalChecks, ShellCheck.Analytics.runTests) where  import ShellCheck.AST@@ -28,6 +29,7 @@ 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@@ -39,6 +41,7 @@ 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)@@ -158,7 +161,6 @@     ,checkWrongArithmeticAssignment     ,checkConditionalAndOrs     ,checkFunctionDeclarations-    ,checkStderrPipe     ,checkOverridingPath     ,checkArrayAsString     ,checkUnsupported@@ -169,6 +171,7 @@     ,checkConcatenatedDollarAt     ,checkTildeInPath     ,checkReadWithoutR+    ,checkCpLegacyR     ,checkLoopVariableReassignment     ,checkTrailingBracket     ,checkReturnAgainstZero@@ -213,13 +216,15 @@ prop_verifyOptionalExamples = all check optionalTreeChecks   where     check (desc, check) =-        verifyTree check (cdPositive desc)+        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\""@@ -227,13 +232,15 @@      ,(newCheckDescription {         cdName = "avoid-nullary-conditions",+        cdId = [2243, 2244],         cdDescription = "Suggest explicitly using -n in `[ $var ]`",-        cdPositive = "[ \"$var\" ]",-        cdNegative = "[ -n \"$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 ]"@@ -241,6 +248,7 @@      ,(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"@@ -248,6 +256,7 @@      ,(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}"@@ -255,6 +264,7 @@      ,(newCheckDescription {         cdName = "check-unassigned-uppercase",+        cdId = [2154],         cdDescription = "Warn when uppercase variables are unassigned",         cdPositive = "echo $VAR",         cdNegative = "VAR=hello; echo $VAR"@@ -262,20 +272,31 @@      ,(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",-        cdNegative = "set -e; func() { cp *.txt ~/backup; rm *.txt; }; func; echo ok"+        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\""@@ -283,6 +304,7 @@      ,(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"@@ -308,6 +330,16 @@ 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 ()@@ -317,9 +349,12 @@ checkUnqualifiedCommand _ _ _ = return ()  verifyCodes :: (Parameters -> Token -> Writer [TokenComment] ()) -> [Code] -> String -> Bool-verifyCodes f l s = codes == Just l+verifyCodes f = verifyCodesTree (runNodeAnalysis f)++verifyCodesTree :: (Parameters -> Token -> [TokenComment]) -> [Code] -> String -> Bool+verifyCodesTree treeCheck l s =+    fmap sort codes == Just (sort l)   where-    treeCheck = runNodeAnalysis f     comments = runAndGetComments treeCheck s     codes = map (cCode . tcComment) <$> comments @@ -347,34 +382,19 @@           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)+              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 (tail n) (tail 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 (tail 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 --- 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-            _ -> []- -- helpers to build replacements replaceStart id params n r =     let tp = tokenPositions params@@ -766,7 +786,9 @@         when v (mapM_ warnFor $ fromWord w)         case getLiteralString w of             Just "-exec" -> broken r True-            Just "-execdir" -> 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@@ -947,12 +969,18 @@ 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-    parts = getWordParts word+    -- 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 ()@@ -986,10 +1014,11 @@ 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 arrayVariables+    defaultSet = S.fromList $ if shellType params == Bash then arrayVariables else []     readF _ (T_DollarBraced id _ token) _ = do         s <- get         return . maybeToList $ do@@ -1063,6 +1092,9 @@ 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}' {} \\;"@@ -1082,6 +1114,15 @@ 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) =@@ -1118,6 +1159,7 @@                 ,"oc"                 ,"dpkg-query"                 ,"jq"  -- could also check that user provides --arg+                ,"yq"                 ,"rename"                 ,"rg"                 ,"unset"@@ -1127,7 +1169,24 @@                 ]             || "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@@ -1136,11 +1195,11 @@             _ -> False      re = mkRegex "\\$[{(0-9a-zA-Z_]|`[^`]+`"-    sedContra = mkRegex "\\$[{dpsaic]($|[^a-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 /= Just "-exec" && x /= Just "-execdir") list+            cmd  = dropWhile (\x -> x `notElem` map Just ["-exec", "-execdir", "-ok", "-okdir"]) list         in           case cmd of             (flag:cmd:rest) -> fromMaybe "find" cmd@@ -1628,7 +1687,7 @@             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+            T_Condition _ _ _ c -> getExpr c             TC_Binary _ _ op lhs rhs -> orient (lhs, op, rhs)             _ -> Nothing @@ -1686,7 +1745,7 @@             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+            T_Condition _ _ _ c -> getExpr c             TC_Binary _ _ op lhs rhs -> orient (lhs, op, rhs)             _ -> Nothing @@ -1706,6 +1765,8 @@ 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."@@ -2065,20 +2126,39 @@ 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 [("oops",[])] Map.empty+        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@((reason,scope):restscope) deadVars =+findSubshelled (Assignment x@(_, _, str, data_):rest) scopes@((kind,scope):restscope) deadVars =     if isTrueAssignmentSource data_-    then findSubshelled rest ((reason, x:scope):restscope) $ Map.insert str Alive deadVars+    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) $ case Map.findWithDefault Alive str deadVars of+    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 ++")."@@ -2086,17 +2166,31 @@     findSubshelled rest scopes deadVars   where     shouldIgnore str =-        str `elem` ["@", "*", "IFS"]+        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 ((reason,[]):scopes) deadVars+    findSubshelled rest ((InSubshell reason,[]):scopes) deadVars -findSubshelled (StackScopeEnd:rest) ((reason, scope):oldScopes) 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.@@ -2334,7 +2428,7 @@ prop_checkFunctionsUsedExternally2b =   verifyNotTree checkFunctionsUsedExternally "alias f='a'; find . -type f" prop_checkFunctionsUsedExternally2c =-  verifyTree checkFunctionsUsedExternally "alias f='a'; find . -type f -exec f +"+  verifyTree checkFunctionsUsedExternally "alias f='a'; find . -type f -exec f {} +" prop_checkFunctionsUsedExternally3 =   verifyNotTree checkFunctionsUsedExternally "f() { :; }; echo f" prop_checkFunctionsUsedExternally4 =@@ -2349,6 +2443,8 @@   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@@ -2376,13 +2472,14 @@             "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"]+        findExecFlags = ["-exec", "-execdir", "-ok", "-okdir"]         dropFlags = dropWhile (\x -> "-" `isPrefixOf` fst x)      functionsAndAliases = Map.union (functions t) (aliases t)@@ -2454,18 +2551,30 @@ 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 (_, token, name, _) <- flow, isVariableName name]+    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) $+        unless ("_" `isPrefixOf` name || hasAllexport params) $             warn (getId token) 2034 $                 name ++ " appears unused. Verify use (or export if used externally)." @@ -2525,6 +2634,13 @@ 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@@ -2618,8 +2734,10 @@ 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"]) $+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 == "?" =@@ -2797,7 +2915,7 @@ 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+    unless (hasErrexit params) $ mapM_ doList $ getCommandSequences t   where     isCdRevert t =         case oversimplify t of@@ -2841,8 +2959,8 @@   where     path = let p = getPath (parentMap params) t in NE.filter relevant p     subshellType t = case leadType params t of-        NoneScope -> Nothing         SubshellScope str -> return str+        _ -> Nothing     relevant t = isLoop t || isFunction t || isJust (subshellType t) checkLoopKeywordScope _ _ = return () @@ -2871,17 +2989,6 @@   -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"@@ -3006,14 +3113,17 @@ 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+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-    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@@ -3245,6 +3355,17 @@  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"@@ -3276,9 +3397,17 @@ 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 hasSetE params then+    if hasErrexit params then         []     else execWriter $ doAnalysis checkElement root   where@@ -3286,6 +3415,7 @@         | 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.")@@ -3293,6 +3423,20 @@         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@@ -3870,6 +4014,13 @@ 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@@ -3880,16 +4031,26 @@   where     findFunction t =         case t of-            T_Function id _ _ name _ -> modify (Map.insertWith (++) name [id])+            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-                invocations <- Map.lookup name funcs+                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?-                guard $ any (\c -> CF.doesPostDominate cfga c id) invocations+                -- 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."@@ -4007,6 +4168,11 @@ 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 _) ->@@ -4015,15 +4181,30 @@                 "-z" -> style (getId t) 2236 "Use -n instead of ! -z."                 _ -> return ()         T_Banged _ (T_Pipeline _ _-          [T_Redirecting _ _ (T_Condition _ _ (TC_Unary _ _ op _))]) ->+          [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 _ _))]) ->+          [T_Redirecting _ _ (T_Condition _ _ _ (TC_Binary _ bracketStyle op _ _))]) ->             maybeSuggestRewrite False bracketStyle (getId t) op         _ -> return ()   where@@ -4135,7 +4316,7 @@ 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 (hasSetE params) $ mapM_ check (getNonReturningCommands t)+checkUselessBang params t = when (hasErrexit params) $ mapM_ check (getNonReturningCommands t)   where     check t =         case t of@@ -4303,6 +4484,7 @@     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@@ -4671,35 +4853,56 @@ 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 _ ->+        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 "[",-                replaceEnd (getId t) params 0 "]"-            ]+            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+        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]}\""@@ -4829,8 +5032,18 @@ 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 hasSetE params then runNodeAnalysis checkNode params t else []+    if hasErrexit params then runNodeAnalysis checkNode params t else []   where     checkNode _ (T_SimpleCommand _ _ (cmd:_)) = when (isFunction cmd) (checkCmd cmd)     checkNode _ _ = return ()@@ -4867,7 +5080,7 @@                 "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+        errExitEnabled t = hasInheritErrexit params || containsErrexit t         isIn t cmds = getId t `elem` map getId cmds  @@ -4909,13 +5122,16 @@ 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_Condition _ _ _ condition) = findMaskedNodesInList [condition]     findMaskingNodes _ (T_DoubleQuoted _ list) = findMaskedNodesInList $ allButLastSimpleCommands list     findMaskingNodes _ (T_HereDoc _ _ _ _ list) = findMaskedNodesInList list     findMaskingNodes _ (T_HereString _ word) = findMaskedNodesInList [word]@@ -4958,7 +5174,7 @@     isMaskDeliberate t = any isOrIf $ NE.init $ parents params t       where         isOrIf (T_OrIf _ _ (T_Pipeline _ _ [T_Redirecting _ _ cmd]))-            = getCommandBasename cmd `elem` [Just "true", Just ":"]+            = getCommandBasename cmd `elem` [Just "true", Just ":", Just "echo"]         isOrIf _ = False      isCheckedElsewhere t = any isDeclaringCommand $ NE.tail $ parents params t@@ -5008,7 +5224,7 @@   where     check commands t =         case t of-            T_Banged id (T_Pipeline _ _ [T_Redirecting _ _ (T_Condition idCondition _ _)]) ->+            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!"@@ -5031,6 +5247,13 @@ 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@@ -5063,9 +5286,19 @@ 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@@ -5079,10 +5312,16 @@          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)) $+            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) $+            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 =@@ -5097,12 +5336,43 @@         all (\c -> CF.doesPostDominate cfga (getId t) c) testIds      isPrinting t =-        case getCommandBasename t of-            Just "echo" -> True-            Just "printf" -> True-            _ -> False+        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"@@ -5213,6 +5483,7 @@             _ -> return ()      checkCmd captureId (T_Redirecting _ redirs _) = foldr (walk captureId) (return ()) redirs+    checkCmd _ _ = return ()      walk captureId t acc =         case t of
src/ShellCheck/AnalyzerLib.hs view
@@ -81,12 +81,16 @@ 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.@@ -112,7 +116,7 @@ -- 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@@ -151,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 =@@ -199,38 +207,43 @@         }     in force withFix +extendedAnalysisAnnotationToMode :: ExtendedAnalysisAnnotation -> ExtendedAnalysisMode+extendedAnalysisAnnotationToMode m =+    case m of+        EAANone -> ExtendedAnalysisNone+        EAALocal -> ExtendedAnalysisLocal+        EAAFull -> ExtendedAnalysisFull+ -- makeParameters :: CheckSpec -> Parameters makeParameters spec = params   where-    extendedAnalysis = fromMaybe True $ msum [asExtendedAnalysis spec, getExtendedAnalysisDirective root]+    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 =-            case shellType params of-                Bash -> isOptionSet "pipefail" root-                Dash -> True-                BusyboxSh -> isOptionSet "pipefail" root-                Sh   -> True-                Ksh  -> isOptionSet "pipefail" root,+        hasPipefail = containsPipefail root,         hasExecfail =             case shellType params of-                Bash -> isOptionSet "execfail" root+                Bash -> containsExecfail root                 _ -> False,         shellTypeSpecified = isJust (asShellType spec) || isJust (asFallbackShell spec),         idMap = getTokenMap root,@@ -238,54 +251,55 @@         variableFlow = getVariableFlow params root,         tokenPositions = asTokenPositions spec,         cfgAnalysis = do-            guard extendedAnalysis+            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@@ -304,14 +318,12 @@ 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@@ -504,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"@@ -587,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@@ -669,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@@ -728,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@@ -802,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@@ -939,6 +972,22 @@         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 [] runTests =  $( [| $(forAllProperties) (quickCheckWithResult (stdArgs { maxSuccess = 1 }) ) |])
src/ShellCheck/CFG.hs view
@@ -160,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@@ -168,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 {@@ -270,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 @@ -293,20 +297,19 @@         )   where     regularEdges = filter isRegularEdge edges-    inDegree = counter $ map (\(from,to,_) -> from) regularEdges-    outDegree = counter $ map (\(from,to,_) -> to) regularEdges+    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 = M.fromList $ map orderEdge $ S.toList edgesToCollapse+    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 (b,a) else (a,b)     counter = M.fromListWith (+) . map (\key -> (key, 1))     isRegularEdge (_, _, CFEFlow) = True     isRegularEdge _ = False@@ -576,16 +579,9 @@          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@@ -612,58 +608,54 @@          T_CaseExpression id t list@(hd:tl) -> do             start <- newStructuralNode-            token <- build t-            branches <- mapM buildBranch (hd NE.:| tl)             end <- newStructuralNode+            token <- build t+            branches <- mapM (buildBranch end) (hd NE.:| tl) -            let neighbors = zip (NE.toList branches) $ NE.tail branches-            let (_, firstCond, _) = NE.head branches-            let (_, lastCond, lastBody) = NE.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@@ -871,11 +863,19 @@          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@@ -899,6 +899,17 @@             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@@ -928,7 +939,7 @@         linkRange condRange end  -handleCommand cmd vars args literalCmd = do+handleCommand simpleCmdToken vars args literalCmd = do     -- TODO: Handle assignments in declaring commands      case literalCmd of@@ -939,6 +950,7 @@         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@@ -958,16 +970,16 @@             case args of                 _ NE.:| [] -> regular                 (_ NE.:| newcmd:newargs) ->-                    handleCommand newcmd vars (newcmd NE.:| newargs) $ getLiteralString newcmd+                    handleCommand simpleCmdToken vars (newcmd NE.:| newargs) $ getLiteralString newcmd         Just "command" ->             case args of                 _ NE.:| [] -> regular                 (_ NE.:| newcmd:newargs) ->-                    handleOthers (getId newcmd) vars (newcmd NE.:| newargs) $ getLiteralString newcmd+                    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@@ -991,7 +1003,7 @@                 unreachable <- newNode CFUnreachable                 return $ Range ret unreachable -    handleUnset (cmd NE.:| args) = do+    handleUnset (_ NE.:| args) = do         case () of                 _ | "n" `elem` flagNames -> unsetWith CFUndefineNameref                 _ | "v" `elem` flagNames -> unsetWith CFUndefineVariable@@ -1010,7 +1022,7 @@      variableAssignRegex = mkRegex "^([_a-zA-Z][_a-zA-Z0-9]*)=" -    handleDeclare (cmd NE.:| 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@@ -1019,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@@ -1029,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 -> Just GlobalScope-                _ | isFunc -> Just LocalScope+                _ | 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 $ [@@ -1099,7 +1116,7 @@             in                 concatMap (drop 1) plusses -    handlePrintf (cmd NE.:| args) =+    handlePrintf (_ NE.:| args) =         newNodeRange $ CFApplyEffects $ maybeToList findVar       where         findVar = do@@ -1108,7 +1125,7 @@             name <- getLiteralString arg             return $ IdTagged (getId arg) $ CFWriteVariable name CFValueString -    handleWait (cmd NE.:| args) =+    handleWait (_ NE.:| args) =         newNodeRange $ CFApplyEffects $ maybeToList findVar       where         findVar = do@@ -1117,11 +1134,11 @@             name <- getLiteralString arg             return $ IdTagged (getId arg) $ CFWriteVariable name CFValueInteger -    handleMapfile (cmd NE.:| 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@@ -1137,7 +1154,7 @@             guard $ isVariableName name             return (getId c, name) -    handleRead (cmd NE.:| args) = newNodeRange $ CFApplyEffects main+    handleRead (_ NE.:| args) = newNodeRange $ CFApplyEffects main       where         main = fromMaybe fallback $ do             flags <- getGnuOpts flagsForRead args@@ -1161,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 NE.:| args) =+    handleDEFINE (_ NE.:| args) =         newNodeRange $ CFApplyEffects $ maybeToList findVar       where         findVar = do@@ -1176,9 +1193,9 @@             guard $ isVariableName str             return $ IdTagged (getId name) $ CFWriteVariable str CFValueString -    handleOthers id vars args cmd =+    handleOthers id vars args maybeName =         regularExpansion vars (NE.toList args) $ do-            exe <- newNodeRange $ CFExecuteCommand cmd+            exe <- newNodeRange $ CFExecuteCommand maybeName             status <- newNodeRange $ CFSetExitCode id             linkRange exe status @@ -1196,9 +1213,9 @@              linkRanges $ [args] ++ assignments ++ [exe] ++ dropAssignments -    regularExpansionWithStatus vars args@(cmd NE.:| _) p = do+    regularExpansionWithStatus vars args p = do         initial <- regularExpansion vars (NE.toList args) p-        status <- newNodeRange $ CFSetExitCode (getId cmd)+        status <- newNodeRange $ CFSetExitCode (getId simpleCmdToken)         linkRange initial status  
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.@@ -61,6 +60,7 @@     ,doesPostDominate     ,variableMayBeDeclaredInteger     ,variableMayBeAssignedInteger+    ,variableMustBeDeclaredReadonly     ,ShellCheck.CFGAnalysis.runTests -- STRIP     ) where @@ -161,9 +161,18 @@     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@@ -448,14 +457,6 @@     stackState :: InternalState }     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.
src/ShellCheck/Checker.hs view
@@ -22,6 +22,8 @@  import ShellCheck.Analyzer import ShellCheck.ASTLib+import ShellCheck.Data (shellFromFilename)+import ShellCheck.EditorConfig import ShellCheck.Interface import ShellCheck.Parser @@ -50,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)@@ -164,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 =@@ -308,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 {@@ -315,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 {@@ -344,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 {@@ -397,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 {@@ -552,15 +699,48 @@ prop_flagWinsWhenSuppressingDfa1 = result == [2317]   where     result = checkWithRc "extended-analysis=false" emptyCheckSpec {-        csScript = "#!/bin/sh\n# shellcheck extended-analysis=false\nexit; foo;",-        csExtendedAnalysis = Just True+        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=true\nexit; foo;",-        csExtendedAnalysis = Just False+        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
@@ -62,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@@ -99,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@@ -118,6 +124,7 @@ optionalCommandChecks = [     (newCheckDescription {         cdName = "deprecate-which",+        cdId = [2230],         cdDescription = "Suggest 'command -v' instead of 'which'",         cdPositive = "which javac",         cdNegative = "command -v javac"@@ -128,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.@@ -400,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 ()@@ -412,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"@@ -424,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"@@ -435,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"@@ -470,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 "[ |;]" @@ -505,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@@ -519,7 +692,7 @@         match (p:tests) args      pattern = [-        (`elem` ["-exec", "-execdir"]),+        (`elem` ["-exec", "-execdir", "-ok", "-okdir"]),         (`elem` ["sh", "bash", "dash", "ksh"]),         (== "-c")         ]@@ -678,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 () @@ -691,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 ->@@ -897,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)) =@@ -907,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"@@ -1086,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@@ -1129,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)@@ -1199,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@@ -1218,32 +1448,32 @@         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         (_,(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?"+        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:"
src/ShellCheck/Checks/ShellSupport.hs view
@@ -148,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"@@ -175,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"@@ -213,7 +213,7 @@ 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 = verify checkBashisms "#!/bin/dash\n$'a'"+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"@@ -223,6 +223,29 @@ 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@@ -238,17 +261,15 @@         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 _) =-        unless isBusyboxSh $ 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 _) =+    bashism (T_Condition id DoubleBracket _ _) =         unless isBusyboxSh $ warnMsg id 3010 "[[ ]] is"     bashism (T_HereString id _) = warnMsg id 3011 "here-strings are" @@ -363,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@@ -383,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@@ -446,7 +467,12 @@             ("readonly", Just ["p"]),             ("trap", Just []),             ("type", Just $ if isBusyboxSh then ["p"] else []),-            ("ulimit", if isDash then Nothing else Just ["f"]),+            ("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 [])@@ -479,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
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,25 +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",-    "BASH_MONOSECONDS", "BASH_TRAPSIG", "GLOBSORT",-    "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"@@ -63,9 +68,6 @@     , "FLAGS_ARGC", "FLAGS_ARGV", "FLAGS_ERROR", "FLAGS_FALSE", "FLAGS_HELP",     "FLAGS_PARENT", "FLAGS_RESERVED", "FLAGS_TRUE", "FLAGS_VERSION",     "flags_error", "flags_return"--    -- Bats-    ,"stderr", "stderr_lines"   ]  specialIntegerVariables = [@@ -104,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 = [@@ -154,6 +156,10 @@     "-o", "-v", "-R"   ] +supportedShellDialects = [+    "sh", "bash", "dash", "ksh", "busybox"+  ]+ shellForExecutable :: String -> Maybe Shell shellForExecutable name =     case name of@@ -171,7 +177,26 @@         "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/JSON1.hs view
@@ -120,7 +120,7 @@         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
src/ShellCheck/Interface.hs view
@@ -37,6 +37,7 @@     , Comment(cSeverity, cCode, cMessage)     , PositionedComment(pcStartPos , pcEndPos , pcComment, pcFix)     , ColorOption(ColorAuto, ColorAlways, ColorNever)+    , ExtendedAnalysisMode(ExtendedAnalysisNone, ExtendedAnalysisLocal, ExtendedAnalysisFull)     , TokenComment(tcId, tcComment, tcFix)     , emptyCheckResult     , newAnalysisResult@@ -57,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 @@ -100,7 +101,7 @@     csIncludedWarnings :: Maybe [Integer],     csShellTypeOverride :: Maybe Shell,     csMinSeverity :: Severity,-    csExtendedAnalysis :: Maybe Bool,+    csExtendedAnalysis :: Maybe ExtendedAnalysisMode,     csOptionalChecks :: [String] } deriving (Show, Eq) @@ -176,7 +177,7 @@     asExecutionMode :: ExecutionMode,     asCheckSourced :: Bool,     asOptionalChecks :: [String],-    asExtendedAnalysis :: Maybe Bool,+    asExtendedAnalysis :: Maybe ExtendedAnalysisMode,     asTokenPositions :: Map.Map Id (Position, Position) } @@ -212,6 +213,7 @@  data CheckDescription = CheckDescription {     cdName :: String,+    cdId :: [Integer],     cdDescription :: String,     cdPositive :: String,     cdNegative :: String@@ -219,6 +221,7 @@  newCheckDescription = CheckDescription {     cdName = "",+    cdId = [],     cdDescription = "",     cdPositive = "",     cdNegative = ""@@ -321,6 +324,13 @@     | ColorAlways     | 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
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@@ -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@@ -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@@ -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@@ -1061,10 +1105,13 @@                 pos <- getPosition                 value <- plainOrQuoted $ many1 letter                 case value of-                    "true" -> return [ExtendedAnalysis True]-                    "false" -> return [ExtendedAnalysis False]+                    "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 true/false."+                        parseNoteAt pos ErrorC 1146 "Unknown extended-analysis value. Expected full/local/none (or true/false)."                         return []              "external-sources" -> do@@ -2060,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 &amp; b"@@ -2069,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 [@@ -2089,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@@ -2106,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"@@ -2124,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@@ -2139,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),@@ -2353,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@@ -2370,8 +2440,9 @@           <|>             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@@ -2391,6 +2462,7 @@  readPipe = do     notFollowedBy2 g_OR_IF+    notFollowedBy2 readKshCoprocessOp     start <- startSpan     char '|'     qualifier <- string "&" <|> return ""@@ -3192,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@@ -3225,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."@@ -3245,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@@ -3290,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 =@@ -3353,13 +3439,19 @@             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@@ -3521,9 +3613,10 @@ 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 script             }
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,6 +12,7 @@ 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@@ -35,6 +36,7 @@       , ("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)