Full Code of koalaman/shellcheck for AI

master cd41f794383b cached
83 files
940.6 KB
255.3k tokens
1 requests
Download .txt
Showing preview only (976K chars total). Download the full file or copy to clipboard to get everything.
Repository: koalaman/shellcheck
Branch: master
Commit: cd41f794383b
Files: 83
Total size: 940.6 KB

Directory structure:
gitextract_k_64siyw/

├── .dockerignore
├── .ghci
├── .github/
│   ├── ISSUE_TEMPLATE/
│   │   ├── bug_report.md
│   │   └── feature_request.md
│   ├── dependabot.yml
│   └── workflows/
│       └── build.yml
├── .github_deploy
├── .gitignore
├── .multi_arch_docker
├── .prepare_deploy
├── .vscode/
│   └── extensions.json
├── CHANGELOG.md
├── Dockerfile.multi-arch
├── LICENSE
├── README.md
├── ShellCheck.cabal
├── builders/
│   ├── README.md
│   ├── build_builder
│   ├── darwin.aarch64/
│   │   ├── Dockerfile
│   │   ├── build
│   │   └── tag
│   ├── darwin.x86_64/
│   │   ├── Dockerfile
│   │   ├── build
│   │   └── tag
│   ├── linux.aarch64/
│   │   ├── Dockerfile
│   │   ├── build
│   │   └── tag
│   ├── linux.armv6hf/
│   │   ├── Dockerfile
│   │   ├── build
│   │   ├── scutil
│   │   └── tag
│   ├── linux.riscv64/
│   │   ├── Dockerfile
│   │   ├── build
│   │   └── tag
│   ├── linux.x86_64/
│   │   ├── Dockerfile
│   │   ├── build
│   │   └── tag
│   ├── run_builder
│   └── windows.x86_64/
│       ├── Dockerfile
│       ├── build
│       └── tag
├── manpage
├── nextnumber
├── quickrun
├── quicktest
├── setgitversion
├── shellcheck.1.md
├── shellcheck.hs
├── snap/
│   └── snapcraft.yaml
├── src/
│   └── ShellCheck/
│       ├── AST.hs
│       ├── ASTLib.hs
│       ├── Analytics.hs
│       ├── Analyzer.hs
│       ├── AnalyzerLib.hs
│       ├── CFG.hs
│       ├── CFGAnalysis.hs
│       ├── Checker.hs
│       ├── Checks/
│       │   ├── Commands.hs
│       │   ├── ControlFlow.hs
│       │   ├── Custom.hs
│       │   └── ShellSupport.hs
│       ├── Data.hs
│       ├── Debug.hs
│       ├── Fixer.hs
│       ├── Formatter/
│       │   ├── CheckStyle.hs
│       │   ├── Diff.hs
│       │   ├── Format.hs
│       │   ├── GCC.hs
│       │   ├── JSON.hs
│       │   ├── JSON1.hs
│       │   ├── Quiet.hs
│       │   └── TTY.hs
│       ├── Interface.hs
│       ├── Parser.hs
│       ├── Prelude.hs
│       └── Regex.hs
├── stack.yaml
├── striptests
└── test/
    ├── buildtest
    ├── check_release
    ├── distrotest
    ├── shellcheck.hs
    └── stacktest

================================================
FILE CONTENTS
================================================

================================================
FILE: .dockerignore
================================================
*
!LICENSE
!Setup.hs
!ShellCheck.cabal
!shellcheck.hs
!src


================================================
FILE: .ghci
================================================
:set -idist/build/autogen -isrc


================================================
FILE: .github/ISSUE_TEMPLATE/bug_report.md
================================================
---
name: Bug report
about: Create a new bug report
title: ''
labels: ''
assignees: ''

---

#### For bugs with existing features

- Rule Id (if any, e.g. SC1000):
- My shellcheck version (`shellcheck --version` or "online"):
- [ ] The rule's wiki page does not already cover this (e.g. https://shellcheck.net/wiki/SC2086)
- [ ] I tried on https://www.shellcheck.net/ and verified that this is still a problem on the latest commit

#### Here's a snippet or screenshot that shows the problem:

```sh
#!/bin/sh
your script here
```

#### Here's what shellcheck currently says:



#### Here's what I wanted or expected to see:


================================================
FILE: .github/ISSUE_TEMPLATE/feature_request.md
================================================
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''

---

#### For new checks and feature suggestions
- [ ] https://www.shellcheck.net/ (i.e. the latest commit) currently gives no useful warnings about this
- [ ] I searched through https://github.com/koalaman/shellcheck/issues and didn't find anything related

#### Here's a snippet or screenshot that shows a potential problem:

```sh
#!/bin/sh
your script here
```

#### Here's what shellcheck currently says:



#### Here's what I wanted to see:


================================================
FILE: .github/dependabot.yml
================================================
version: 2

updates:
  - package-ecosystem: "github-actions"
    directory: "/"
    schedule:
      interval: "daily"


================================================
FILE: .github/workflows/build.yml
================================================
name: Build ShellCheck

# Run this workflow every time a new commit pushed to your repository
on: [push, pull_request]

jobs:
  package_source:
    name: Package Source Code
    runs-on: ubuntu-latest
    steps:
      - name: Install Dependencies
        run: |
          sudo apt-get update
          sudo apt-mark manual ghc # Don't bother installing ghc just to tar up source
          sudo apt-get install cabal-install

      - name: Checkout repository
        uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - name: Deduce tags
        run: |
          mkdir source
          echo "latest" > source/tags
          if tag=$(git describe --exact-match --tags)
          then
            echo "stable" >> source/tags
            echo "$tag" >> source/tags
          fi
          cat source/tags

      - name: Package Source
        run: |
          grep "stable" source/tags || ./setgitversion
          cabal sdist
          mv dist-newstyle/sdist/*.tar.gz source/source.tar.gz

      - name: Upload artifact
        uses: actions/upload-artifact@v6
        with:
          name: source
          path: source/

  run_tests:
    name: Run tests (GHC ${{ matrix.ghc }})
    needs: package_source
    runs-on: ubuntu-latest
    strategy:
      matrix:
        ghc: ['8.0', '8.10', '9.0.1', '9.4.7', '9.6.6', 'latest']
        include:
          - ghc: 'latest'
            cabal_flags: '--allow-newer'
      # If one version fails, we still want the status of the others
      fail-fast: false
    steps:
      - name: Download artifacts
        uses: actions/download-artifact@v7
        with:
          name: source
          path: source/

      - name: Setup Haskell
        uses: haskell-actions/setup@v2
        with:
          ghc-version: ${{ matrix.ghc }}

      - name: Unpack source
        run: |
          cd source
          tar xvf source.tar.gz --strip-components=1

      - name: Build and run tests
        run: |
          cd source
          cabal test ${{ matrix.cabal_flags }}

  build_source:
    name: Build
    needs: package_source
    strategy:
      matrix:
        build: [linux.x86_64, linux.aarch64, linux.armv6hf, linux.riscv64, darwin.x86_64, darwin.aarch64, windows.x86_64]
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v6

      - name: Download artifacts
        uses: actions/download-artifact@v7
        with:
          name: source
          path: source/

      - name: Build source
        run: |
          mkdir -p bin
          mkdir -p bin/${{matrix.build}}
          ( cd bin && ../builders/run_builder ../source/source.tar.gz ../builders/${{matrix.build}} )

      - name: Upload artifact
        uses: actions/upload-artifact@v6
        with:
          name: ${{matrix.build}}.bin
          path: bin/

  package_binary:
    name: Package Binaries
    needs: build_source
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v6

      - name: Download artifacts
        uses: actions/download-artifact@v7

      - name: List files for debugging
        run: find .

      - name: Work around GitHub permissions bug
        run: chmod +x *.bin/*/shellcheck*

      - name: Package binaries
        run: |
          export TAGS="$(cat source/tags)"
          mkdir -p deploy
          cp -r *.bin/* deploy
          cd deploy
          ../.prepare_deploy
          rm -rf */ README* LICENSE*

      - name: Upload artifact
        uses: actions/upload-artifact@v6
        with:
          name: deploy
          path: deploy/

  deploy:
    if: github.event_name == 'push'
    name: Deploy binaries
    needs: package_binary
    runs-on: ubuntu-latest
    environment: Deploy
    steps:
      - name: Install Dependencies
        run: |
          sudo apt-get update
          sudo apt-get install hub

      - name: Checkout repository
        uses: actions/checkout@v6

      - name: Download artifacts (source)
        uses: actions/download-artifact@v7
        with:
          name: source
          path: source/

      - name: Download artifacts (binaries)
        uses: actions/download-artifact@v7
        with:
          name: deploy
          path: deploy/

      - name: Upload to GitHub
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          export TAGS="$(cat source/tags)"
          ./.github_deploy

      - name: Waiting for GitHub to replicate uploaded releases
        run: |
          sleep 300

      - name: Upload to Docker Hub
        env:
          DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
          DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }}
          DOCKER_EMAIL: ${{ secrets.DOCKER_EMAIL }}
          DOCKER_BASE: ${{ secrets.DOCKER_USERNAME }}/shellcheck
        run: |
          export TAGS="$(cat source/tags)"
          ( source ./.multi_arch_docker && set -eux && multi_arch_docker::main )


================================================
FILE: .github_deploy
================================================
#!/bin/bash
set -x
shopt -s extglob

export EDITOR="touch"

# Sanity check
gh --version || exit 1
hub release show latest || exit 1

for tag in $TAGS
do
  if ! hub release show "$tag"
  then
    echo "Creating new release $tag"
    git show --no-patch  --format='format:%B' > description
    hub release create -F description "$tag"
  fi

  files=()
  for file in deploy/*
  do
    [[ $file == *.@(xz|gz|zip) ]] || continue
    [[ $file == *"$tag"* ]] || continue
    files+=("$file")
  done
  gh release upload "$tag" "${files[@]}" --clobber || exit 1
done


================================================
FILE: .gitignore
================================================
# Created by https://www.gitignore.io

### Haskell ###
dist
cabal-dev
*.o
*.hi
*.chi
*.chs.h
.virtualenv
.hsenv
.cabal-sandbox/
cabal.sandbox.config
cabal.config
cabal.project.freeze
.stack-work
stack.yaml.lock

### Snap ###
/snap/.snapcraft/
/stage/
/parts/
/prime/
*.snap
/dist-newstyle/

### misc ###
/shellcheck.1


================================================
FILE: .multi_arch_docker
================================================
#!/bin/bash
# This script builds and deploys multi-architecture docker images from the
# binaries previously built and deployed to GitHub.

function multi_arch_docker::install_docker_buildx() {
  # Install QEMU multi-architecture support for docker buildx.
  docker run --rm --privileged multiarch/qemu-user-static --reset -p yes

  # Instantiate docker buildx builder with multi-architecture support.
  docker buildx create --name mybuilder
  docker buildx use mybuilder
  # Start up buildx and verify that all is OK.
  docker buildx inspect --bootstrap
}

# Log in to Docker Hub for deployment.
function multi_arch_docker::login_to_docker_hub() {
  echo "$DOCKER_PASSWORD" | docker login -u="$DOCKER_USERNAME" --password-stdin
}

# Run buildx build and push. Passed in arguments augment the command line.
function multi_arch_docker::buildx() {
  mkdir -p /tmp/empty
  docker buildx build \
    --platform "${DOCKER_PLATFORMS// /,}" \
    --push \
    --progress plain \
    -f Dockerfile.multi-arch \
    "$@" \
    /tmp/empty
  rmdir /tmp/empty
}

# Build and push plain and alpine docker images for all tags.
function multi_arch_docker::build_and_push_all() {
  for tag in $TAGS; do
    multi_arch_docker::buildx -t "$DOCKER_BASE:$tag" --build-arg "tag=$tag"
    multi_arch_docker::buildx -t "$DOCKER_BASE-alpine:$tag" \
      --build-arg "tag=$tag" --target alpine
  done
}

# Test all pushed docker images.
function multi_arch_docker::test_all() {
  printf '%s\n' "#!/bin/sh" "echo 'hello world'" > myscript

  for platform in $DOCKER_PLATFORMS; do
    for tag in $TAGS; do
      for ext in '-alpine' ''; do
        image="${DOCKER_BASE}${ext}:${tag}"
        msg="Testing docker image $image on platform $platform"
        line="${msg//?/=}"
        printf '\n%s\n%s\n%s\n' "${line}" "${msg}" "${line}"
        docker pull -q --platform "$platform" "$image"
        if [ -n "$ext" ]; then
          echo -n "Image architecture: "
          docker run --rm --entrypoint /bin/sh "$image" -c 'uname -m'
          version=$(docker run --rm "$image" shellcheck --version \
            | grep 'version:')
        else
          version=$(docker run --rm "$image" --version | grep 'version:')
        fi
        version=${version/#version: /v}
        echo "shellcheck version: $version"
        if [[ ! ("$tag" =~ ^(latest|stable)$) && "$tag" != "$version" ]]; then
          echo "Version mismatch: shellcheck $version tagged as $tag"
          exit 1
        fi
        if [ -n "$ext" ]; then
          docker run --rm -v "$PWD:/mnt" -w /mnt "$image" shellcheck myscript
        else
          docker run --rm -v "$PWD:/mnt" "$image" myscript
        fi
      done
    done
  done
}

function multi_arch_docker::main() {
  export DOCKER_PLATFORMS='linux/amd64'
  DOCKER_PLATFORMS+=' linux/arm64'
  DOCKER_PLATFORMS+=' linux/arm/v6'
  DOCKER_PLATFORMS+=' linux/riscv64'

  multi_arch_docker::install_docker_buildx
  multi_arch_docker::login_to_docker_hub
  multi_arch_docker::build_and_push_all
  multi_arch_docker::test_all
}


================================================
FILE: .prepare_deploy
================================================
#!/bin/bash
# This script packages up compiled binaries
set -ex
shopt -s nullglob extglob

ls -l

cp ../LICENSE LICENSE.txt
sed -e $'s/$/\r/' > README.txt << END
This is a precompiled ShellCheck binary.
      https://www.shellcheck.net/

ShellCheck is a static analysis tool for shell scripts.
It's licensed under the GNU General Public License v3.0.
Information and source code is available on the website.

This binary was compiled on $(date -u).



      ====== Latest commits ======

$(git log -n 3)
END

for dir in */
do
  cp LICENSE.txt README.txt "$dir"
done

echo "Tags are $TAGS"

for tag in $TAGS
do

  for dir in windows.*/
  do
    ( cd "$dir" && zip "../shellcheck-$tag.zip" * )
  done

  for dir in {linux,darwin}.*/
  do
    base="${dir%/}"
    ( cd "$dir" && tar -cJf "../shellcheck-$tag.$base.tar.xz" --transform="s:^:shellcheck-$tag/:" * )
    ( cd "$dir" && tar -czf "../shellcheck-$tag.$base.tar.gz" --transform="s:^:shellcheck-$tag/:" * )
  done
done

for file in ./*
do
  [[ -f "$file" ]] || continue
  sha512sum "$file" > "$file.sha512sum"
done

ls -l


================================================
FILE: .vscode/extensions.json
================================================
{
    "recommendations": [
        "haskell.haskell",
    ],
}


================================================
FILE: CHANGELOG.md
================================================
## Git
### Added

### Changed

### Fixed

### Removed
- SC3003: removed since ANSI C string is specified in POSIX.1-2024


## v0.11.0 - 2025-08-03
### Added
- SC2327/SC2328: Warn about capturing the output of redirected commands.
- SC2329: Warn when (non-escaping) functions are never invoked.
- SC2330: Warn about unsupported glob matches with [[ .. ]] in BusyBox.
- SC2331: Suggest using standard -e instead of unary -a in tests.
- SC2332: Warn about `[ ! -o opt ]` being unconditionally true in Bash.
- SC3062: Warn about bashism `[ -o opt ]`.
- Optional `avoid-negated-conditions`: suggest replacing `[ ! a -eq b ]`
  with `[ a -ne b ]`, and similar for -ge/-lt/=/!=/etc (SC2335).
- Precompiled binaries for Linux riscv64 (linux.riscv64)

### Changed
- SC2002 about Useless Use Of Cat is now disabled by default. It can be
  re-enabled with `--enable=useless-use-of-cat` or equivalent directive.
- SC2236/SC2237 about replacing `[ ! -n .. ]` with `[ -z ]` and vice versa
  is now optional under `avoid-negated-conditions`.
- SC2015 about `A && B || C` no longer triggers when B is a test command.
- SC3012: Do not warn about `\<` and `\>` in test/[] as specified in POSIX.1-2024
- Diff output now uses / as path separator on Windows

### Fixed
- SC2218 about function use-before-define is now more accurate.
- SC2317 about unreachable commands is now less spammy for nested ones.
- SC2292, optional suggestion for [[ ]], now triggers for Busybox.
- Updates for Bash 5.3, including `${| cmd; }` and `source -p`

### Removed
- SC3013: removed since the operators `-ot/-nt/-ef` are specified in POSIX.1-2024


## v0.10.0 - 2024-03-07
### Added
- Precompiled binaries for macOS ARM64 (darwin.aarch64)
- Added support for busybox sh
- Added flag --rcfile to specify an rc file by name.
- Added `extended-analysis=true` directive to enable/disable dataflow analysis
  (with a corresponding --extended-analysis flag).
- SC2324: Warn when x+=1 appends instead of increments
- SC2325: Warn about multiple `!`s in dash/sh.
- SC2326: Warn about `foo | ! bar` in bash/dash/sh.
- SC3012: Warn about lexicographic-compare bashism in test like in [ ]
- SC3013: Warn bashism `test _ -op/-nt/-ef _` like in [ ]
- SC3014: Warn bashism `test _ == _` like in [ ]
- SC3015: Warn bashism `test _ =~ _` like in [ ]
- SC3016: Warn bashism `test -v _` like in [ ]
- SC3017: Warn bashism `test -a _` like in [ ]

### Fixed
- source statements with here docs now work correctly
- "(Array.!): undefined array element" error should no longer occur


## v0.9.0 - 2022-12-12
### Added
- SC2316: Warn about 'local readonly foo' and similar (thanks, patrickxia!)
- SC2317: Warn about unreachable commands
- SC2318: Warn about backreferences in 'declare x=1 y=$x'
- SC2319/SC2320: Warn when $? refers to echo/printf/[ ]/[[ ]]/test
- SC2321: Suggest removing $((..)) in array[$((idx))]=val
- SC2322: Suggest collapsing double parentheses in arithmetic contexts
- SC2323: Suggest removing wrapping parentheses in a[(x+1)]=val

### Fixed
- SC2086: Now uses DFA to make more accurate predictions about values
- SC2086: No longer warns about values declared as integer with declare -i

### Changed
- ShellCheck now has a Data Flow Analysis engine to make smarter decisions
  based on control flow rather than just syntax. Existing checks will
  gradually start using it, which may cause them to trigger differently
  (but more accurately).
- Values in directives/shellcheckrc can now be quoted with '' or ""


## v0.8.0 - 2021-11-06
### Added
- `disable=all` now conveniently disables all warnings
- `external-sources=true` directive can be added to .shellcheckrc to make
  shellcheck behave as if `-x` was specified.
- Optional `check-extra-masked-returns` for pointing out commands with
  suppressed exit codes (SC2312).
- Optional `require-double-brackets` for recommending \[\[ ]] (SC2292).
- SC2286-SC2288: Warn when command name ends in a symbol like `/.)'"`
- SC2289: Warn when command name contains tabs or linefeeds
- SC2291: Warn about repeated unquoted spaces between words in echo
- SC2292: Suggest [[ over [ in Bash/Ksh scripts (optional)
- SC2293/SC2294: Warn when calling `eval` with arrays
- SC2295: Warn about "${x#$y}" treating $y as a pattern when not quoted
- SC2296-SC2301: Improved warnings for bad parameter expansions
- SC2302/SC2303: Warn about loops over array values when using them as keys
- SC2304-SC2306: Warn about unquoted globs in expr arguments
- SC2307: Warn about insufficient number of arguments to expr
- SC2308: Suggest other approaches for non-standard expr extensions
- SC2313: Warn about `read` with unquoted, array indexed variable

### Fixed
- SC2102 about repetitions in ranges no longer triggers on [[ -v arr[xx] ]]
- SC2155 now recognizes `typeset` and local read-only `declare` statements
- SC2181 now tries to avoid triggering for error handling functions
- SC2290: Warn about misused = in declare & co, which were not caught by SC2270+
- The flag --color=auto no longer outputs color when TERM is "dumb" or unset

### Changed
- SC2048: Warning about $\* now also applies to ${array[\*]}
- SC2181 now only triggers on single condition tests like `[ $? = 0 ]`.
- Quote warnings are now emitted for declaration utilities in sh
- Leading `_` can now be used to suppress warnings about unused variables
- TTY output now includes warning level in text as well as color

### Removed
- SC1004: Literal backslash+linefeed in '' was found to be usually correct


## v0.7.2 - 2021-04-19
### Added
- `disable` directives can now be a range, e.g. `disable=SC3000-SC4000`
- SC1143: Warn about line continuations in comments
- SC2259/SC2260: Warn when redirections override pipes
- SC2261: Warn about multiple competing redirections
- SC2262/SC2263: Warn about aliases declared and used in the same parsing unit
- SC2264: Warn about wrapper functions that blatantly recurse
- SC2265/SC2266: Warn when using & or | with test statements
- SC2267: Warn when using xargs -i instead of -I
- SC2268: Warn about unnecessary x-comparisons like `[ x$var = xval ]`

### Fixed
- SC1072/SC1073 now respond to disable annotations, though ignoring parse errors
  is still purely cosmetic and does not allow ShellCheck to continue.
- Improved error reporting for trailing tokens after ]/]] and compound commands
- `#!/usr/bin/env -S shell` is now handled correctly
- Here docs with \r are now parsed correctly and give better warnings

### Changed
- Assignments are now parsed to spec, without leniency for leading $ or spaces
- POSIX/dash unsupported feature warnings now have individual SC3xxx codes
- SC1090: A leading `$x/` or `$(x)/` is now treated as `./` when locating files
- SC2154: Variables appearing in -z/-n tests are no longer considered unassigned
- SC2270-SC2285: Improved warnings about misused `=`, e.g. `${var}=42`


## v0.7.1 - 2020-04-04
### Fixed
- `-f diff` no longer claims that it found more issues when it didn't
- Known empty variables now correctly trigger SC2086
- ShellCheck should now be compatible with Cabal 3
- SC2154 and all command-specific checks now trigger for builtins
  called with `builtin`

### Added
- SC1136: Warn about unexpected characters after ]/]]
- SC2254: Suggest quoting expansions in case statements
- SC2255: Suggest using `$((..))` in `[ 2*3 -eq 6 ]`
- SC2256: Warn about translated strings that are known variables
- SC2257: Warn about arithmetic mutation in redirections
- SC2258: Warn about trailing commas in for loop elements

### Changed
- SC2230: 'command -v' suggestion is now off by default (-i deprecate-which)
- SC1081: Keywords are now correctly parsed case sensitively, with a warning


## v0.7.0 - 2019-07-28
### Added
- Precompiled binaries for macOS and Linux aarch64
- Preliminary support for fix suggestions
- New `-f diff` unified diff format for auto-fixes
- Files containing Bats tests can now be checked
- Directory wide directives can now be placed in a `.shellcheckrc`
- Optional checks: Use `--list-optional` to show a list of tests,
                   Enable with `-o` flags or `enable=name` directives
- Source paths: Use `-P dir1:dir2` or a `source-path=dir1` directive
                to specify search paths for sourced files.
- json1 format like --format=json but treats tabs as single characters
- Recognize FLAGS variables created by the shflags library.
- Site-specific changes can now be made in Custom.hs for ease of patching
- SC2154: Also warn about unassigned uppercase variables (optional)
- SC2252: Warn about `[ $a != x ] || [ $a != y ]`, similar to SC2055
- SC2251: Inform about ineffectual ! in front of commands
- SC2250: Warn about variable references without braces (optional)
- SC2249: Warn about `case` with missing default case (optional)
- SC2248: Warn about unquoted variables without special chars (optional)
- SC2247: Warn about $"(cmd)" and $"{var}"
- SC2246: Warn if a shebang's interpreter ends with /
- SC2245: Warn that Ksh ignores all but the first glob result in `[`
- SC2243/SC2244: Suggest using explicit -n for `[ $foo ]` (optional)
- SC1135: Suggest not ending double quotes just to make $ literal

### Changed
- If a directive or shebang is not specified, a `.bash/.bats/.dash/.ksh`
  extension will be used to infer the shell type when present.
- Disabling SC2120 on a function now disables SC2119 on call sites

### Fixed
- SC2183 no longer warns about missing printf args for `%()T`

## v0.6.0 - 2018-12-02
### Added
- Command line option --severity/-S for filtering by minimum severity
- Command line option --wiki-link-count/-W for showing wiki links
- SC2152/SC2151: Warn about bad `exit` values like `1234` and `"foo"`
- SC2236/SC2237: Suggest -n/-z instead of ! -z/-n
- SC2238: Warn when redirecting to a known command name, e.g. ls > rm
- SC2239: Warn if the shebang is not an absolute path, e.g. #!bin/sh
- SC2240: Warn when passing additional arguments to dot (.) in sh/dash
- SC1133: Better diagnostics when starting a line with |/||/&&

### Changed
- Most warnings now have useful end positions
- SC1117 about unknown double-quoted escape sequences has been retired

### Fixed
- SC2021 no longer triggers for equivalence classes like `[=e=]`
- SC2221/SC2222 no longer mistriggers on fall-through case branches
- SC2081 about glob matches in `[ .. ]` now also triggers for `!=`
- SC2086 no longer warns about spaces in `$#`
- SC2164 no longer suggests subshells for `cd ..; cmd; cd ..`
- `read -a` is now correctly considered an array assignment
- SC2039 no longer warns about LINENO now that it's POSIX

## v0.5.0 - 2018-05-31
### Added
- SC2233/SC2234/SC2235: Suggest removing or replacing (..) around tests
- SC2232: Warn about invalid arguments to sudo
- SC2231: Suggest quoting expansions in for loop globs
- SC2229: Warn about 'read $var'
- SC2227: Warn about redirections in the middle of 'find' commands
- SC2224/SC2225/SC2226: Warn when using mv/cp/ln without a destination
- SC2223: Quote warning specific to `: ${var=value}`
- SC1131: Warn when using `elseif` or `elsif`
- SC1128: Warn about blanks/comments before shebang
- SC1127: Warn about C-style comments

### Fixed
- Annotations intended for a command's here documents now work
- Escaped characters inside groups in =~ regexes now parse
- Associative arrays are now respected in arithmetic contexts
- SC1087 about `$var[@]` now correctly triggers on any index
- Bad expansions in here documents are no longer ignored
- FD move operations like {fd}>1- now parse correctly

### Changed
- Here docs are now terminated as per spec, rather than by presumed intent
- SC1073: 'else if' is now parsed correctly and not like 'elif'
- SC2163: 'export $name' can now be silenced with 'export ${name?}'
- SC2183: Now warns when printf arg count is not a multiple of format count

## v0.4.7 - 2017-12-08
### Added
- Statically linked binaries for Linux and Windows (see README.md)!
- `-a` flag to also include warnings in `source`d files
- SC2221/SC2222: Warn about overridden case branches
- SC2220: Warn about unhandled error cases in getopt loops
- SC2218: Warn when using functions before they're defined
- SC2216/SC2217: Warn when piping/redirecting to mv/cp and other non-readers
- SC2215: Warn about commands starting with leading dash
- SC2214: Warn about superfluous getopt flags
- SC2213: Warn about unhandled getopt flags
- SC2212: Suggest `false` over `[ ]`
- SC2211: Warn when using a glob as a command name
- SC2210: Warn when redirecting to an integer, e.g. `foo 1>2`
- SC2206/SC2207: Suggest alternatives when using word splitting in arrays
- SC1117: Warn about double quoted, undefined backslash sequences
- SC1113/SC1114/SC1115: Recognized more malformed shebangs

### Fixed
- `[ -v foo ]` no longer warns if `foo` is undefined
- SC2037 is now suppressed by quotes, e.g. `PAGER="cat" man foo`
- Ksh nested array declarations now parse correctly
- Parameter Expansion without colons are now recognized, e.g. `${foo+bar}`
- The `lastpipe` option is now respected with regard to subshell warnings
- `\(` is now respected for grouping in `[`
- Leading `\` is now ignored for commands, to allow alias suppression
- Comments are now allowed after directives to e.g. explain 'disable'


## v0.4.6 - 2017-03-26
### Added
- SC2204/SC2205: Warn about `( -z foo )` and `( foo -eq bar )`
- SC2200/SC2201: Warn about brace expansion in [/[[
- SC2198/SC2199: Warn about arrays in [/[[
- SC2196/SC2197: Warn about deprecated egrep/fgrep
- SC2195: Warn about unmatchable case branches
- SC2194: Warn about constant 'case' statements
- SC2193: Warn about `[[ file.png == *.mp3 ]]` and other unmatchables
- SC2188/SC2189: Warn about redirections without commands
- SC2186: Warn about deprecated `tempfile`
- SC1109: Warn when finding `&amp;`/`&gt;`/`&lt;` unquoted
- SC1108: Warn about missing spaces in `[ var= foo ]`

### Changed
- All files are now read as UTF-8 with lenient latin1 fallback, ignoring locale
- Unicode quotes are no longer considered syntactic quotes
- `ash` scripts will now be checked as `dash` with a warning

### Fixed
- `-c` no longer suggested when using `grep -o | wc`
- Comments and whitespace are now allowed before filewide directives
- Here doc delimiters with esoteric quoting like `foo""` are now handled
- SC2095 about `ssh` in while read loops is now suppressed when using `-n`
- `%(%Y%M%D)T` now recognized as a single formatter in `printf` checks
- `grep -F` now suppresses regex related suggestions
- Command name checks now recognize busybox applet names


## v0.4.5 - 2016-10-21
### Added
- A Docker build (thanks, kpankonen!)
- SC2185: Suggest explicitly adding path for `find`
- SC2184: Warn about unsetting globs (e.g. `unset foo[1]`)
- SC2183: Warn about `printf` with more formatters than variables
- SC2182: Warn about ignored arguments with `printf`
- SC2181: Suggest using command directly instead of `if [ $? -eq 0 ]`
- SC1106: Warn when using `test` operators in `(( 1 -eq 2 ))`

### Changed
- Unrecognized directives now causes a warning rather than parse failure.

### Fixed
- Indices in associative arrays are now parsed correctly
- Missing shebang warning squashed when specifying with a directive
- Ksh multidimensional arrays are now supported
- Variables in substring ${a:x:y} expansions now count as referenced
- SC1102 now also handles ambiguous `$((`
- Using `$(seq ..)` will no longer suggest quoting
- SC2148 (missing shebang) is now suppressed when using shell directives
- `[ a '>' b ]` is now recognized as being correctly escaped


## v0.4.4 - 2016-05-15
### Added
- Haskell Stack support (thanks,  Arguggi!)
- SC2179/SC2178: Warn when assigning/appending strings to arrays
- SC1102: Warn about ambiguous `$(((`
- SC1101: Warn when \\ linebreaks have trailing spaces

### Changed
- Directives directly after the shebang now apply to the entire file

### Fixed
- `{$i..10}` is now flagged similar to `{1..$i}`


## v0.4.3 - 2016-01-13
### Fixed
- Build now works on GHC 7.6.3 as found on Debian Stable/Ubuntu LTS


## v0.4.2 - 2016-01-09
### Added
- First class support for the `dash` shell
- The `--color` flag similar to ls/grep's (thanks, haguenau!)
- SC2174: Warn about unexpected behavior of `mkdir -pm` (thanks, eatnumber1!)
- SC2172: Warn about non-portable use of signal numbers in `trap`
- SC2171: Warn about `]]` without leading `[[`
- SC2168: Warn about `local` outside functions

### Fixed
- Warnings about unchecked `cd` will no longer trigger with `set -e`
- `[ a -nt/-ot/-ef b ]` no longer warns about being constant
- Quoted test operators like `[ foo "<" bar ]` now parse
- Escaped quotes in backticks now parse correctly


## v0.4.1 - 2015-09-05
### Fixed
- Added missing files to Cabal, fixing the build


## v0.4.0 - 2015-09-05
### Added
- Support for following `source`d files
- Support for setting default flags in `SHELLCHECK_OPTS`
- An `--external-sources` flag for following arbitrary `source`d files
- A `source` directive to override the filename to `source`
- SC2166: Suggest using `[ p ] && [ q ]` over `[ p -a q ]`
- SC2165: Warn when nested `for` loops use the same variable name
- SC2164: Warn when using `cd` without checking that it succeeds
- SC2163: Warn about `export $var`
- SC2162: Warn when using `read` without `-r`
- SC2157: Warn about `[ "$var " ]` and similar never-empty string matches

### Fixed
- `cat -vnE file` and similar will no longer flag as UUOC
- Nested trinary operators in `(( ))` now parse correctly
- Ksh `${ ..; }` command expansions now parse


## v0.3.8 - 2015-06-20
### Changed
- ShellCheck's license has changed from AGPLv3 to GPLv3.

### Added
- SC2156: Warn about injecting filenames in `find -exec sh -c "{}" \;`

### Fixed
- Variables and command substitutions in brace expansions are now parsed
- ANSI colors are now disabled on Windows
- Empty scripts now parse


## v0.3.7 - 2015-04-16
### Fixed
- Build now works on GHC 7.10
- Use `regex-tdfa` over `regex-compat` since the latter crashes on OS X.

## v0.3.6 - 2015-03-28
### Added
- SC2155: Warn about masked return values in `export foo=$(exit 1)`
- SC2154: Warn when a lowercase variable is referenced but not assigned
- SC2152/SC2151: Warn about bad `return` values like `1234` and `"foo"`
- SC2150: Warn about `find -exec "shell command" \;`

### Fixed
- `coproc` is now supported
- Trinary operator now recognized in `((..))`

### Removed
- Zsh support has been removed


## v0.3.5 - 2014-11-09
### Added
- SC2148: Warn when not including a shebang
- SC2147: Warn about literal ~ in PATH
- SC1086: Warn about `$` in for loop variables, e.g. `for $i in ..`
- SC1084: Warn when the shebang uses `!#` instead of `#!`

### Fixed
- Empty and comment-only backtick expansions now parse
- Variables used in PS1/PROMPT\_COMMAND/trap now count as referenced
- ShellCheck now skips unreadable files and directories
- `-f gcc` on empty files no longer crashes
- Variables in $".." are now considered quoted
- Warnings about expansions in single quotes now include backticks


## v0.3.4 - 2014-07-08
### Added
- SC2146: Warn about precedence when combining `find -o` with actions
- SC2145: Warn when concatenating arrays and strings

### Fixed
- Case statements now support `;&` and `;;&`
- Indices in array declarations now parse correctly
- `let` expressions now parsed as arithmetic expressions
- Escaping is now respected in here documents

### Changed
- Completely drop Makefile in favor of Cabal (thanks rodrigosetti!)


## v0.3.3 - 2014-05-29
### Added
- SC2144: Warn when using globs in `[/[[`
- SC2143: Suggesting using `grep -q` over `[ "$(.. | grep)" ]`
- SC2142: Warn when referencing positional parameters in aliases
- SC2141: Warn about suspicious IFS assignments like `IFS="\n"`
- SC2140: Warn about bad embedded quotes like `echo "var="value""`
- SC2130: Warn when using `-eq` on strings
- SC2139: Warn about define time expansions in alias definitions
- SC2129: Suggest command grouping over `a >> log; b >> log; c >> log`
- SC2128: Warn when expanding arrays without an index
- SC2126: Suggest `grep -c` over `grep|wc`
- SC2123: Warn about accidentally overriding `$PATH`, e.g. `PATH=/my/dir`
- SC1083: Warn about literal `{/}` outside of quotes
- SC1082: Warn about UTF-8 BOMs

### Fixed
- SC2051 no longer triggers for `{1,$n}`, only `{1..$n}`
- Improved detection of single quoted `sed` variables, e.g. `sed '$s///'`
- Stop warning about single quoted variables in `PS1` and similar
- Support for Zsh short form loops, `=(..)`

### Removed
- SC1000 about unescaped lonely `$`, e.g. `grep "^foo$"`


## v0.3.2 - 2014-03-22
### Added
- SC2121: Warn about trying to `set` variables, e.g. `set var = value`
- SC2120/SC2119: Warn when a function uses `$1..` if none are ever passed
- SC2117: Warn when using `su` in interactive mode, e.g. `su foo; whoami`
- SC2116: Detect useless use of echo, e.g. `for i in $(echo $var)`
- SC2115/SC2114: Detect some catastrophic `rm -r "$empty/"` mistakes
- SC1081: Warn when capitalizing keywords like `While`
- SC1077: Warn when using acute accents instead of backticks

### Fixed
- Shells are now properly recognized in shebangs containing flags
- Stop warning about math on decimals in ksh/zsh
- Stop warning about decimal comparisons with `=`, e.g. `[ $version = 1.2 ]`
- Parsing of `|&`
- `${a[x]}` not counting as a reference of `x`
- `(( x[0] ))` not counting as a reference of `x`


## v0.3.1 - 2014-02-03
### Added
- The `-s` flag to specify shell dialect
- SC2105/SC2104: Warn about `break/continue` outside loops
- SC1076: Detect invalid `[/[[` arithmetic like `[ 1 + 2 = 3 ]`
- SC1075: Suggest using `elif` over `else if`

### Fixed
- Don't warn when comma separating elements in brace expansions
- Improved detection of single quoted `sed` variables, e.g. `sed '$d'`
- Parsing of arithmetic for loops using `{..}` instead of `do..done`
- Don't treat the last pipeline stage as a subshell in ksh/zsh


## v0.3.0 - 2014-01-19
### Added
- A man page (thanks Dridi!)
- GCC compatible error reporting (`shellcheck -f gcc`)
- CheckStyle compatible XML error reporting (`shellcheck -f checkstyle`)
- Error codes for each warning, e.g. SC1234
- Allow disabling warnings with `# shellcheck disable=SC1234`
- Allow disabling warnings with `--exclude`
- SC2103: Suggest using subshells over `cd foo; bar; cd ..`
- SC2102: Warn about duplicates in char ranges, e.g. `[10-15]`
- SC2101: Warn about named classes not inside a char range, e.g. `[:digit:]`
- SC2100/SC2099: Warn about bad math expressions like `i=i+5`
- SC2098/SC2097: Warn about `foo=bar echo $foo`
- SC2095: Warn when using `ssh`/`ffmpeg` in `while read` loops
- Better warnings for missing here doc tokens

### Fixed
- Don't warn when single quoting variables with `ssh/perl/eval`
- `${!var}` is now counted as a variable reference

### Removed
- Suggestions about using parameter expansion over basename
- The `jsoncheck` binary. Use `shellcheck -f json` instead.


## v0.2.0 - 2013-10-27
### Added
- Suggest `./*` instead of `*` when passing globs to commands
- Suggest `pgrep` over `ps | grep`
- Warn about unicode quotes
- Warn about assigned but unused variables
- Inform about client side expansion when using `ssh`

### Fixed
- CLI tool now uses exit codes and stderr canonically
- Parsing of extglobs containing empty patterns
- Parsing of bash style `eval foo=(bar)`
- Parsing of expansions in here documents
- Parsing of function names containing :+-
- Don't warn about `find|xargs` when using `-print0`


## v0.1.0 - 2013-07-23
### Added
- First release


================================================
FILE: Dockerfile.multi-arch
================================================
# Alpine image
FROM alpine:latest AS alpine
LABEL maintainer="Vidar Holen <vidar@vidarholen.net>"
ARG tag

# Put the right binary for each architecture into place for the
# multi-architecture docker image.
ARG url_base="https://github.com/koalaman/shellcheck/releases/download/"
RUN set -x; \
  arch="$(uname -m)"; \
  echo "arch is $arch"; \
  if [ "${arch}" = 'armv7l' ]; then \
    arch='armv6hf'; \
  fi; \
  tar_file="${tag}/shellcheck-${tag}.linux.${arch}.tar.xz"; \
  wget "${url_base}${tar_file}" -O - | tar -C /bin --strip-components=1 -xJf - "shellcheck-${tag}/shellcheck" && \
  ls -laF /bin/shellcheck

# ShellCheck image
FROM scratch
LABEL maintainer="Vidar Holen <vidar@vidarholen.net>"
WORKDIR /mnt
COPY --from=alpine /bin/shellcheck /bin/
ENTRYPOINT ["/bin/shellcheck"]


================================================
FILE: LICENSE
================================================
                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program 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.

    This program 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/>.

Also add information on how to contact you by electronic and paper mail.

  If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    <program>  Copyright (C) <year>  <name of author>
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.


================================================
FILE: README.md
================================================
[![Build Status](https://github.com/koalaman/shellcheck/actions/workflows/build.yml/badge.svg)](https://github.com/koalaman/shellcheck/actions/workflows/build.yml)


# ShellCheck - A shell script static analysis tool

ShellCheck is a GPLv3 tool that gives warnings and suggestions for bash/sh shell scripts:

![Screenshot of a terminal showing problematic shell script lines highlighted](doc/terminal.png)

The goals of ShellCheck are

* To point out and clarify typical beginner's syntax issues that cause a shell
  to give cryptic error messages.

* To point out and clarify typical intermediate level semantic problems that
  cause a shell to behave strangely and counter-intuitively.

* To point out subtle caveats, corner cases and pitfalls that may cause an
  advanced user's otherwise working script to fail under future circumstances.

See [the gallery of bad code](README.md#user-content-gallery-of-bad-code) for examples of what ShellCheck can help you identify!

## Table of Contents

* [How to use](#how-to-use)
  * [On the web](#on-the-web)
  * [From your terminal](#from-your-terminal)
  * [In your editor](#in-your-editor)
  * [In your build or test suites](#in-your-build-or-test-suites)
* [Installing](#installing)
* [Compiling from source](#compiling-from-source)
  * [Installing Cabal](#installing-cabal)
  * [Compiling ShellCheck](#compiling-shellcheck)
  * [Running tests](#running-tests)
* [Gallery of bad code](#gallery-of-bad-code)
  * [Quoting](#quoting)
  * [Conditionals](#conditionals)
  * [Frequently misused commands](#frequently-misused-commands)
  * [Common beginner's mistakes](#common-beginners-mistakes)
  * [Style](#style)
  * [Data and typing errors](#data-and-typing-errors)
  * [Robustness](#robustness)
  * [Portability](#portability)
  * [Miscellaneous](#miscellaneous)
* [Testimonials](#testimonials)
* [Ignoring issues](#ignoring-issues)
* [Reporting bugs](#reporting-bugs)
* [Contributing](#contributing)
* [Copyright](#copyright)
* [Other Resources](#other-resources)

## How to use

There are a number of ways to use ShellCheck!

### On the web

Paste a shell script on <https://www.shellcheck.net> for instant feedback.

[ShellCheck.net](https://www.shellcheck.net) is always synchronized to the latest git commit, and is the easiest way to give ShellCheck a go. Tell your friends!

### From your terminal

Run `shellcheck yourscript` in your terminal for instant output, as seen above.

### In your editor

You can see ShellCheck suggestions directly in a variety of editors.

* Vim, through [ALE](https://github.com/w0rp/ale), [Neomake](https://github.com/neomake/neomake), or [Syntastic](https://github.com/scrooloose/syntastic):

![Screenshot of Vim showing inlined shellcheck feedback](doc/vim-syntastic.png).

* Emacs, through [Flycheck](https://github.com/flycheck/flycheck) or [Flymake](https://github.com/federicotdn/flymake-shellcheck):

![Screenshot of emacs showing inlined shellcheck feedback](doc/emacs-flycheck.png).

* Sublime, through [SublimeLinter](https://github.com/SublimeLinter/SublimeLinter-shellcheck).

* Pulsar Edit (former Atom), through [linter-shellcheck-pulsar](https://github.com/pulsar-cooperative/linter-shellcheck-pulsar).

* VSCode, through [vscode-shellcheck](https://github.com/timonwong/vscode-shellcheck).

* Most other editors, through [GCC error compatibility](shellcheck.1.md#user-content-formats).

### In your build or test suites

While ShellCheck is mostly intended for interactive use, it can easily be added to builds or test suites.
It makes canonical use of exit codes, so you can just add a `shellcheck` command as part of the process.

For example, in a Makefile:

```Makefile
check-scripts:
    # Fail if any of these files have warnings
    shellcheck myscripts/*.sh
```

or in a Travis CI `.travis.yml` file:

```yaml
script:
  # Fail if any of these files have warnings
  - shellcheck myscripts/*.sh
```

Services and platforms that have ShellCheck pre-installed and ready to use:

* [Travis CI](https://travis-ci.org/)
* [Codacy](https://www.codacy.com/)
* [Code Climate](https://codeclimate.com/)
* [Code Factor](https://www.codefactor.io/)
* [Codety](https://www.codety.io/) via the [Codety Scanner](https://github.com/codetyio/codety-scanner)
* [CircleCI](https://circleci.com) via the [ShellCheck Orb](https://circleci.com/orbs/registry/orb/circleci/shellcheck)
* [Github](https://github.com/features/actions) (only Linux)
* [Trunk Code Quality](https://trunk.io/code-quality) (universal linter; [allows you to explicitly version your shellcheck install](https://github.com/trunk-io/plugins/blob/bcbb361dcdbe4619af51ea7db474d7fb87540d20/.trunk/trunk.yaml#L32)) via the [shellcheck plugin](https://github.com/trunk-io/plugins/blob/main/linters/shellcheck/plugin.yaml)
* [CodeRabbit](https://coderabbit.ai/)

Most other services, including [GitLab](https://about.gitlab.com/), let you install
ShellCheck yourself, either through the system's package manager (see [Installing](#installing)),
or by downloading and unpacking a [binary release](#installing-a-pre-compiled-binary).

It's a good idea to manually install a specific ShellCheck version regardless. This avoids
any surprise build breaks when a new version with new warnings is published.

For customized filtering or reporting, ShellCheck can output simple JSON, CheckStyle compatible XML,
GCC compatible warnings as well as human readable text (with or without ANSI colors). See the
[Integration](https://github.com/koalaman/shellcheck/wiki/Integration) wiki page for more documentation.

## Installing

The easiest way to install ShellCheck locally is through your package manager.

On systems with Cabal (installs to `~/.cabal/bin`):

    cabal update
    cabal install ShellCheck

On systems with Stack (installs to `~/.local/bin`):

    stack update
    stack install ShellCheck

On Debian based distros:

    sudo apt install shellcheck

On Arch Linux based distros:

    pacman -S shellcheck

or get the dependency free [shellcheck-bin](https://aur.archlinux.org/packages/shellcheck-bin/) from the AUR.

On Gentoo based distros:

    emerge --ask shellcheck

On EPEL based distros:

    sudo yum -y install epel-release
    sudo yum install ShellCheck

On Fedora based distros:

    dnf install ShellCheck

On FreeBSD:

    pkg install hs-ShellCheck

On macOS (OS X) with Homebrew:

    brew install shellcheck

Or with MacPorts:

    sudo port install shellcheck

On OpenBSD:

    pkg_add shellcheck

On openSUSE

    zypper in ShellCheck

Or use OneClickInstall - <https://software.opensuse.org/package/ShellCheck>

On Solus:

    eopkg install shellcheck

On Windows (via [chocolatey](https://chocolatey.org/packages/shellcheck)):

```cmd
C:\> choco install shellcheck
```

Or Windows (via [winget](https://github.com/microsoft/winget-pkgs)):

```cmd
C:\> winget install --id koalaman.shellcheck
```

Or Windows (via [scoop](http://scoop.sh)):

```cmd
C:\> scoop install shellcheck
```

From [conda-forge](https://anaconda.org/conda-forge/shellcheck):

    conda install -c conda-forge shellcheck

From Snap Store:

    snap install --channel=edge shellcheck

From Docker Hub:

```sh
docker run --rm -v "$PWD:/mnt" koalaman/shellcheck:stable myscript
# Or :v0.4.7 for that version, or :latest for daily builds
```

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 the [nix package manager](https://nixos.org/nix):
```sh
nix-env -iA nixpkgs.shellcheck
```

Using the [Flox package manager](https://flox.dev/)
```sh
flox install shellcheck
```

Alternatively, you can download pre-compiled binaries for the latest release here:

* [Linux, x86_64](https://github.com/koalaman/shellcheck/releases/download/stable/shellcheck-stable.linux.x86_64.tar.xz) (statically linked)
* [Linux, armv6hf](https://github.com/koalaman/shellcheck/releases/download/stable/shellcheck-stable.linux.armv6hf.tar.xz), i.e. Raspberry Pi (statically linked)
* [Linux, aarch64](https://github.com/koalaman/shellcheck/releases/download/stable/shellcheck-stable.linux.aarch64.tar.xz) aka ARM64 (statically linked)
* [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)

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
pandoc -s -f markdown-smart -t man shellcheck.1.md -o shellcheck.1
sudo mv shellcheck.1 /usr/share/man/man1
```

### pre-commit

To run ShellCheck via [pre-commit](https://pre-commit.com/), add the hook to your `.pre-commit-config.yaml`:

```
repos:
-   repo: https://github.com/koalaman/shellcheck-precommit
    rev: v0.11.0
    hooks:
    -   id: shellcheck
#       args: ["--severity=warning"]  # Optionally only show errors and warnings
```

### Travis CI

Travis CI has now integrated ShellCheck by default, so you don't need to manually install it.

If you still want to do so in order to upgrade at your leisure or ensure you're
using the latest release, follow the steps below to install a binary version.

### Installing a pre-compiled binary

The pre-compiled binaries come in `tar.xz` files. To decompress them, make sure
`xz` is installed.
On Debian/Ubuntu/Mint, you can `apt install xz-utils`.
On Redhat/Fedora/CentOS, `yum -y install xz`.

A simple installer may do something like:

```bash
scversion="stable" # or "v0.4.7", or "latest"
wget -qO- "https://github.com/koalaman/shellcheck/releases/download/${scversion?}/shellcheck-${scversion?}.linux.x86_64.tar.xz" | tar -xJv
cp "shellcheck-${scversion}/shellcheck" /usr/bin/
shellcheck --version
```

## Compiling from source

This section describes how to build ShellCheck from a source directory. ShellCheck is written in Haskell and requires 2GB of RAM to compile.

### Installing Cabal

ShellCheck is built and packaged using Cabal. Install the package `cabal-install` from your system's package manager (with e.g. `apt-get`, `brew`, `emerge`, `yum`, or `zypper`).

On macOS (OS X), you can do a fast install of Cabal using brew, which takes a couple of minutes instead of more than 30 minutes if you try to compile it from source.

    $ brew install cabal-install

On MacPorts, the package is instead called `hs-cabal-install`, while native Windows users should install the latest version of the Haskell platform from <https://www.haskell.org/platform/>

Verify that `cabal` is installed and update its dependency list with

    $ cabal update

### Compiling ShellCheck

`git clone` this repository, and `cd` to the ShellCheck source directory to build/install:

    $ cabal install

This will compile ShellCheck and install it to your `~/.cabal/bin` directory.

Add this directory to your `PATH` (for bash, add this to your `~/.bashrc`):

```sh
export PATH="$HOME/.cabal/bin:$PATH"
```

Log out and in again, and verify that your PATH is set up correctly:

```sh
$ which shellcheck
~/.cabal/bin/shellcheck
```

On native Windows, the `PATH` should already be set up, but the system
may use a legacy codepage. In `cmd.exe`, `powershell.exe` and Powershell ISE,
make sure to use a TrueType font, not a Raster font, and set the active
codepage to UTF-8 (65001) with `chcp`:

```cmd
chcp 65001
```

In Powershell ISE, you may need to additionally update the output encoding:

```powershell
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
```

### Running tests

To run the unit test suite:

    $ cabal test

## Gallery of bad code

So what kind of things does ShellCheck look for? Here is an incomplete list of detected issues.

### Quoting

ShellCheck can recognize several types of incorrect quoting:

```sh
echo $1                           # Unquoted variables
find . -name *.ogg                # Unquoted find/grep patterns
rm "~/my file.txt"                # Quoted tilde expansion
v='--verbose="true"'; cmd $v      # Literal quotes in variables
for f in "*.ogg"                  # Incorrectly quoted 'for' loops
touch $@                          # Unquoted $@
echo 'Don't forget to restart!'   # Singlequote closed by apostrophe
echo 'Don\'t try this at home'    # Attempting to escape ' in ''
echo 'Path is $PATH'              # Variables in single quotes
trap "echo Took ${SECONDS}s" 0    # Prematurely expanded trap
unset var[i]                      # Array index treated as glob
```

### Conditionals

ShellCheck can recognize many types of incorrect test statements.

```sh
[[ n != 0 ]]                      # Constant test expressions
[[ -e *.mpg ]]                    # Existence checks of globs
[[ $foo==0 ]]                     # Always true due to missing spaces
[[ -n "$foo " ]]                  # Always true due to literals
[[ $foo =~ "fo+" ]]               # Quoted regex in =~
[ foo =~ re ]                     # Unsupported [ ] operators
[ $1 -eq "shellcheck" ]           # Numerical comparison of strings
[ $n && $m ]                      # && in [ .. ]
[ grep -q foo file ]              # Command without $(..)
[[ "$$file" == *.jpg ]]           # Comparisons that can't succeed
(( 1 -lt 2 ))                     # Using test operators in ((..))
[ x ] & [ y ] | [ z ]             # Accidental backgrounding and piping
```

### Frequently misused commands

ShellCheck can recognize instances where commands are used incorrectly:

```sh
grep '*foo*' file                 # Globs in regex contexts
find . -exec foo {} && bar {} \;  # Prematurely terminated find -exec
sudo echo 'Var=42' > /etc/profile # Redirecting sudo
time --format=%s sleep 10         # Passing time(1) flags to time builtin
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'
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
```

### Common beginner's mistakes

ShellCheck recognizes many common beginner's syntax errors:

```sh
var = 42                          # Spaces around = in assignments
$foo=42                           # $ in assignments
for $var in *; do ...             # $ in for loop variables
var$n="Hello"                     # Wrong indirect assignment
echo ${var$n}                     # Wrong indirect reference
var=(1, 2, 3)                     # Comma separated arrays
array=( [index] = value )         # Incorrect index initialization
echo $var[14]                     # Missing {} in array references
echo "Argument 10 is $10"         # Positional parameter misreference
if $(myfunction); then ..; fi     # Wrapping commands in $()
else if othercondition; then ..   # Using 'else if'
f; f() { echo "hello world; }     # Using function before definition
[ false ]                         # 'false' being true
if ( -f file )                    # Using (..) instead of test
```

### Style

ShellCheck can make suggestions to improve style:

```sh
[[ -z $(find /tmp | grep mpg) ]]  # Use grep -q instead
a >> log; b >> log; c >> log      # Use a redirection block instead
echo "The time is `date`"         # Use $() instead
cd dir; process *; cd ..;         # Use subshells instead
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
```

### Data and typing errors

ShellCheck can recognize issues related to data and typing:

```sh
args="$@"                         # Assigning arrays to strings
files=(foo bar); echo "$files"    # Referencing arrays as strings
declare -A arr=(foo bar)          # Associative arrays without index
printf "%s\n" "Arguments: $@."    # Concatenating strings and arrays
[[ $# > 2 ]]                      # Comparing numbers as strings
var=World; echo "Hello " var      # Unused lowercase variables
echo "Hello $name"                # Unassigned lowercase variables
cmd | read bar; echo $bar         # Assignments in subshells
cat foo | cp bar                  # Piping to commands that don't read
printf '%s: %s\n' foo             # Mismatches in printf argument count
eval "${array[@]}"                # Lost word boundaries in array eval
for i in "${x[@]}"; do ${x[$i]}   # Using array value as key
```

### Robustness

ShellCheck can make suggestions for improving the robustness of a script:

```sh
rm -rf "$STEAMROOT/"*            # Catastrophic rm
touch ./-l; ls *                 # Globs that could become options
find . -exec sh -c 'a && b {}' \; # Find -exec shell injection
printf "Hello $name"             # Variables in printf format
for f in $(ls *.txt); do         # Iterating over ls output
export MYVAR=$(cmd)              # Masked exit codes
case $version in 2.*) :;; 2.6.*) # Shadowed case branches
```

### Portability

ShellCheck will warn when using features not supported by the shebang. For example, if you set the shebang to `#!/bin/sh`, ShellCheck will warn about portability issues similar to `checkbashisms`:

```sh
echo {1..$n}                     # Works in ksh, but not bash/dash/sh
echo {1..10}                     # Works in ksh and bash, but not dash/sh
echo -n 42                       # Works in ksh, bash and dash, undefined in sh
expr match str regex             # Unportable alias for `expr str : regex`
trap 'exit 42' sigint            # Unportable signal spec
cmd &> file                      # Unportable redirection operator
read foo < /dev/tcp/host/22      # Unportable intercepted files
foo-bar() { ..; }                # Undefined/unsupported function name
[ $UID = 0 ]                     # Variable undefined in dash/sh
local var=value                  # local is undefined in sh
time sleep 1 | sleep 5           # Undefined uses of 'time'
```

### Miscellaneous

ShellCheck recognizes a menagerie of other issues:

```sh
PS1='\e[0;32m\$\e[0m '            # PS1 colors not in \[..\]
PATH="$PATH:~/bin"                # Literal tilde in $PATH
rm “file”                         # Unicode quotes
echo "Hello world"                # Carriage return / DOS line endings
echo hello \                      # Trailing spaces after \
var=42 echo $var                  # Expansion of inlined environment
!# bin/bash -x -e                 # Common shebang errors
echo $((n/180*100))               # Unnecessary loss of precision
ls *[:digit:].txt                 # Bad character class globs
sed 's/foo/bar/' file > file      # Redirecting to input
var2=$var2                        # Variable assigned to itself
[ 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
while getopts "a" f; do case $f in "b") # Unhandled getopts flags
```

## Testimonials

> At first you're like "shellcheck is awesome" but then you're like "wtf are we still using bash"

Alexander Tarasikov,
[via Twitter](https://twitter.com/astarasikov/status/568825996532707330)

## Ignoring issues

Issues can be ignored via environmental variable, command line, individually or globally within a file:

<https://github.com/koalaman/shellcheck/wiki/Ignore>

## Reporting bugs

Please use the GitHub issue tracker for any bugs or feature suggestions:

<https://github.com/koalaman/shellcheck/issues>

## Contributing

Please submit patches to code or documentation as GitHub pull requests! Check
out the [DevGuide](https://github.com/koalaman/shellcheck/wiki/DevGuide) on the
ShellCheck Wiki.

Contributions must be licensed under the GNU GPLv3.
The contributor retains the copyright.

## Copyright

ShellCheck is licensed under the GNU General Public License, v3. A copy of this license is included in the file [LICENSE](LICENSE).

Copyright 2012-2019, [Vidar 'koala_man' Holen](https://github.com/koalaman/) and contributors.

Happy ShellChecking!

## Other Resources

* The wiki has [long form descriptions](https://github.com/koalaman/shellcheck/wiki/Checks) for each warning, e.g. [SC2221](https://github.com/koalaman/shellcheck/wiki/SC2221).
* ShellCheck does not attempt to enforce any kind of formatting or indenting style, so also check out [shfmt](https://github.com/mvdan/sh)!


================================================
FILE: ShellCheck.cabal
================================================
Name:             ShellCheck
Version:          0.11.0
Synopsis:         Shell script analysis tool
License:          GPL-3
License-file:     LICENSE
Category:         Static Analysis
Author:           Vidar Holen
Maintainer:       vidar@vidarholen.net
Homepage:         https://www.shellcheck.net/
Build-Type:       Simple
Cabal-Version:    1.18
Bug-reports:      https://github.com/koalaman/shellcheck/issues
Description:
  The goals of ShellCheck are:
  .
  * To point out and clarify typical beginner's syntax issues,
    that causes a shell to give cryptic error messages.
  .
  * To point out and clarify typical intermediate level semantic problems,
    that causes a shell to behave strangely and counter-intuitively.
  .
  * 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
Extra-Source-Files:
    -- documentation
    shellcheck.1.md
    -- A script to build the man page using pandoc
    manpage
    -- convenience script for stripping tests
    striptests
    -- tests
    test/shellcheck.hs

source-repository head
    type: git
    location: https://github.com/koalaman/shellcheck.git

library
    hs-source-dirs: src
    if impl(ghc < 8.0)
      build-depends:
        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,
      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.2 && < 1.6,
      Diff                 >= 0.4.0 && < 1.1,
      fgl                  (>= 5.7.0 && < 5.8.1.0) || (>= 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,
      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
    exposed-modules:
      ShellCheck.AST
      ShellCheck.ASTLib
      ShellCheck.Analytics
      ShellCheck.Analyzer
      ShellCheck.AnalyzerLib
      ShellCheck.CFG
      ShellCheck.CFGAnalysis
      ShellCheck.Checker
      ShellCheck.Checks.Commands
      ShellCheck.Checks.ControlFlow
      ShellCheck.Checks.Custom
      ShellCheck.Checks.ShellSupport
      ShellCheck.Data
      ShellCheck.Debug
      ShellCheck.Fixer
      ShellCheck.Formatter.Format
      ShellCheck.Formatter.CheckStyle
      ShellCheck.Formatter.Diff
      ShellCheck.Formatter.GCC
      ShellCheck.Formatter.JSON
      ShellCheck.Formatter.JSON1
      ShellCheck.Formatter.TTY
      ShellCheck.Formatter.Quiet
      ShellCheck.Interface
      ShellCheck.Parser
      ShellCheck.Prelude
      ShellCheck.Regex
    other-modules:
      Paths_ShellCheck
    default-language: Haskell2010

executable shellcheck
    if impl(ghc < 8.0)
      build-depends:
        semigroups
    build-depends:
      aeson,
      array,
      base,
      bytestring,
      containers,
      deepseq,
      Diff,
      directory,
      fgl,
      mtl,
      filepath,
      parsec,
      QuickCheck,
      regex-tdfa,
      transformers,
      ShellCheck
    default-language: Haskell2010
    main-is: shellcheck.hs

test-suite test-shellcheck
    type: exitcode-stdio-1.0
    build-depends:
      aeson,
      array,
      base,
      bytestring,
      containers,
      deepseq,
      Diff,
      directory,
      fgl,
      filepath,
      mtl,
      parsec,
      QuickCheck,
      regex-tdfa,
      transformers,
      ShellCheck
    default-language: Haskell2010
    main-is: test/shellcheck.hs


================================================
FILE: builders/README.md
================================================
This directory contains Dockerfiles for all builds.

A build image will:

* Run on Linux x86\_64 with vanilla Docker (no exceptions)
* Not contain any software that would restrict easy modification or copying
* Take a `cabal sdist` style tar.gz of the ShellCheck directory on stdin
* Output a tar.gz of artifacts on stdout, in a directory named for the arch

This makes it simple to build any release without exotic hardware or software.

An image can be built and tagged using `build_builder`,
and run on a source tarball using `run_builder`.

Tip: Are you developing an image that relies on QEmu usermode emulation?
     It's easy to accidentally depend on binfmt\_misc on the host OS.
     Do a `echo 0 | sudo tee /proc/sys/fs/binfmt_misc/status` before testing.


================================================
FILE: builders/build_builder
================================================
#!/bin/sh
if [ $# -eq 0 ]
then
  echo >&2 "No build image directories specified"
  echo >&2 "Example: $0 build/*/"
  exit 1
fi

for dir
do
  ( cd "$dir" && docker build -t "$(cat tag)" . ) || exit 1
done


================================================
FILE: builders/darwin.aarch64/Dockerfile
================================================
FROM ghcr.io/shepherdjerred/macos-cross-compiler@sha256:7d40c5e179d5d15453cf2a6b1bba3392bb1448b8257ee6b86021fc905c59dad6

ENV TARGET=aarch64-apple-darwin22
ENV TARGETNAME=darwin.aarch64

# Build dependencies
USER root
ENV DEBIAN_FRONTEND=noninteractive
ENV LC_ALL=C.utf8

# Install basic deps
RUN apt-get update && apt-get install -y automake autoconf build-essential curl xz-utils qemu-user-static

# Install a more suitable host compiler
WORKDIR /host-ghc
RUN curl -L "https://downloads.haskell.org/~cabal/cabal-install-3.9.0.0/cabal-install-3.9-x86_64-linux-alpine.tar.xz" | tar xJv -C /usr/local/bin
RUN curl -L 'https://downloads.haskell.org/~ghc/8.10.7/ghc-8.10.7-x86_64-deb10-linux.tar.xz' | tar xJ --strip-components=1
RUN ./configure && make install

# Build GHC. We have to use an old version because cross-compilation across OS has since broken.
WORKDIR /ghc
RUN curl -L "https://downloads.haskell.org/~ghc/8.10.7/ghc-8.10.7-src.tar.xz" | tar xJ --strip-components=1
RUN apt-get install -y llvm-12
RUN ./boot && ./configure --host x86_64-linux-gnu --build x86_64-linux-gnu --target "$TARGET"
RUN cp mk/flavours/quick-cross.mk mk/build.mk && make -j "$(nproc)"
RUN make install

# Due to an apparent cabal bug, we specify our options directly to cabal
# It won't reuse caches if ghc-options are specified in ~/.cabal/config
ENV CABALOPTS="--ghc-options;-optc-Os -optc-fPIC;--with-ghc=$TARGET-ghc;--with-hc-pkg=$TARGET-ghc-pkg;--constraint=hashable==1.3.5.0"

# Prebuild the dependencies
RUN cabal update
RUN IFS=';' && cabal install --dependencies-only $CABALOPTS ShellCheck

# Copy the build script
COPY build /usr/bin

WORKDIR /scratch
ENTRYPOINT ["/usr/bin/build"]


================================================
FILE: builders/darwin.aarch64/build
================================================
#!/bin/sh
set -xe
{
  tar xzv --strip-components=1
  chmod +x striptests && ./striptests
  mkdir "$TARGETNAME"
  ( IFS=';'; cabal build $CABALOPTS )
  find . -name shellcheck -type f -exec mv {} "$TARGETNAME/" \;
  ls -l "$TARGETNAME"
  # Stripping invalidates the code signature and the build image does
  # not appear to have anything similar to the 'codesign' tool.
  # "$TARGET-strip" "$TARGETNAME/shellcheck"
  ls -l "$TARGETNAME"
  file "$TARGETNAME/shellcheck" | grep "Mach-O 64-bit arm64 executable"
} >&2
tar czv "$TARGETNAME"


================================================
FILE: builders/darwin.aarch64/tag
================================================
koalaman/scbuilder-darwin-aarch64


================================================
FILE: builders/darwin.x86_64/Dockerfile
================================================
FROM liushuyu/osxcross@sha256:fa32af4677e2860a1c5950bc8c360f309e2a87e2ddfed27b642fddf7a6093b76

ENV TARGET=x86_64-apple-darwin18
ENV TARGETNAME=darwin.x86_64

# Build dependencies
USER root
ENV DEBIAN_FRONTEND=noninteractive
RUN sed -e 's/focal/kinetic/g' -e 's/archive\|security/old-releases/' -i /etc/apt/sources.list
RUN apt-get update
RUN apt-get dist-upgrade -y
RUN apt-get install -y ghc automake autoconf llvm curl alex happy

# Build GHC
WORKDIR /ghc
RUN curl -L "https://downloads.haskell.org/~ghc/9.2.8/ghc-9.2.8-src.tar.xz" | tar xJ --strip-components=1
RUN ./configure --host x86_64-linux-gnu --build x86_64-linux-gnu --target "$TARGET"
RUN cp mk/flavours/quick-cross.mk mk/build.mk && make -j "$(nproc)"
RUN make install
RUN curl -L "https://downloads.haskell.org/~cabal/cabal-install-3.9.0.0/cabal-install-3.9-x86_64-linux-alpine.tar.xz" | tar xJv -C /usr/local/bin

# Due to an apparent cabal bug, we specify our options directly to cabal
# It won't reuse caches if ghc-options are specified in ~/.cabal/config
ENV CABALOPTS="--with-ghc=$TARGET-ghc;--with-hc-pkg=$TARGET-ghc-pkg"

# Prebuild the dependencies
RUN cabal update && IFS=';' && cabal install --dependencies-only $CABALOPTS ShellCheck

# Copy the build script
COPY build /usr/bin

WORKDIR /scratch
ENTRYPOINT ["/usr/bin/build"]


================================================
FILE: builders/darwin.x86_64/build
================================================
#!/bin/sh
set -xe
{
  tar xzv --strip-components=1
  chmod +x striptests && ./striptests
  mkdir "$TARGETNAME"
  ( IFS=';'; cabal build $CABALOPTS )
  find . -name shellcheck -type f -exec mv {} "$TARGETNAME/" \;
  ls -l "$TARGETNAME"
  "$TARGET-strip" -Sx "$TARGETNAME/shellcheck"
  ls -l "$TARGETNAME"
} >&2
tar czv "$TARGETNAME"


================================================
FILE: builders/darwin.x86_64/tag
================================================
koalaman/scbuilder-darwin-x86_64


================================================
FILE: builders/linux.aarch64/Dockerfile
================================================
FROM ubuntu:25.04

ENV TARGET=aarch64-linux-gnu
ENV TARGETNAME=linux.aarch64

# Build dependencies
USER root
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y llvm-20 "gcc-$TARGET" "g++-$TARGET" ghc alex happy automake autoconf build-essential curl qemu-user-static
RUN curl -L "https://downloads.haskell.org/~cabal/cabal-install-3.16.0.0/cabal-install-3.16.0.0-x86_64-linux-alpine3_20.tar.xz" | tar xJv -C /usr/local/bin && cabal update

# Build GHC
WORKDIR /ghc
RUN curl -L "https://downloads.haskell.org/~ghc/9.12.2/ghc-9.12.2-src.tar.xz" | tar xJ --strip-components=1
RUN ./boot.source && ./configure --host x86_64-linux-gnu --build x86_64-linux-gnu --target "$TARGET"
# GHC fails to build if it can't encode non-ascii
ENV LC_CTYPE=C.utf8
# We have to do a binary-dist instead of a direct install, otherwise the targest won't have
# cross compilation prefixes in /usr/local/lib/aarch64-linux-gnu-ghc-*/lib/settings
RUN ./hadrian/build --flavour=quickest --bignum=native -V -j --prefix=/usr/local install
# Hadrian just outputs "gcc" as the name of gcc, without accounting for $TARGET. Manually fix up the paths:
RUN sed -e 's/"\(gcc\|g++\|ld\)"/"'"$TARGET"'-\1"/g' -i /usr/local/lib/$TARGET-ghc-*/lib/settings

# Due to an apparent cabal bug, we specify our options directly to cabal
# It won't reuse caches if ghc-options are specified in ~/.cabal/config
ENV CABALOPTS="--ghc-options;-split-sections -optc-Os -optc-Wl,--gc-sections -optc-fPIC;--with-compiler=$TARGET-ghc;--with-hc-pkg=$TARGET-ghc-pkg;-c;hashable -arch-native"

# Prebuild the dependencies
RUN cabal update && IFS=';' && cabal install --dependencies-only $CABALOPTS ShellCheck

# Copy the build script
COPY build /usr/bin

WORKDIR /scratch
ENTRYPOINT ["/usr/bin/build"]


================================================
FILE: builders/linux.aarch64/build
================================================
#!/bin/sh
set -xe
{
  tar xzv --strip-components=1
  chmod +x striptests && ./striptests
  mkdir "$TARGETNAME"
  ( IFS=';'; cabal build $CABALOPTS --enable-executable-static )
  find . -name shellcheck -type f -exec mv {} "$TARGETNAME/" \;
  ls -l "$TARGETNAME"
  "$TARGET-strip" -s "$TARGETNAME/shellcheck"
  ls -l "$TARGETNAME"
  "qemu-${TARGET%%-*}-static" "$TARGETNAME/shellcheck" --version
} >&2
tar czv "$TARGETNAME"


================================================
FILE: builders/linux.aarch64/tag
================================================
koalaman/scbuilder-linux-aarch64


================================================
FILE: builders/linux.armv6hf/Dockerfile
================================================
# This Docker file uses a custom QEmu fork with patches to follow execve
# to build all of ShellCheck emulated.

FROM ubuntu:25.04

ENV TARGETNAME linux.armv6hf

# Build QEmu with execve follow support
USER root
ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update
RUN apt-get install -y --no-install-recommends build-essential git ninja-build python3 pkg-config libglib2.0-dev libpixman-1-dev python3-setuptools ca-certificates debootstrap
WORKDIR /qemu
RUN git clone --depth 1 https://github.com/koalaman/qemu .
RUN ./configure --static --disable-werror && cd build && ninja qemu-arm
ENV QEMU_EXECVE 1

# Convenience utility
COPY scutil /bin/scutil
COPY scutil /chroot/bin/scutil
RUN chmod +x /bin/scutil /chroot/bin/scutil

# Set up an armv6 userspace
WORKDIR /
RUN debootstrap --arch armhf --variant=minbase --foreign bookworm /chroot http://mirrordirector.raspbian.org/raspbian
RUN cp /qemu/build/qemu-arm /chroot/bin/qemu
RUN scutil emu /debootstrap/debootstrap --second-stage

# Install deps in the chroot
RUN scutil emu apt-get update
RUN scutil emu apt-get install -y --no-install-recommends ghc cabal-install
RUN scutil emu cabal update

# Finally we can build the current dependencies. This takes hours.
ENV CABALOPTS "--ghc-options;-split-sections -optc-Os -optc-Wl,--gc-sections;--gcc-options;-Os -Wl,--gc-sections -ffunction-sections -fdata-sections"
# Generated with `cabal freeze --constraint 'hashable -arch-native'`
COPY cabal.project.freeze /chroot/etc
RUN IFS=";" && scutil install_from_freeze /chroot/etc/cabal.project.freeze emu cabal install $CABALOPTS

# Copy the build script
COPY build /chroot/bin
ENTRYPOINT ["/bin/scutil", "emu", "/bin/build"]


================================================
FILE: builders/linux.armv6hf/build
================================================
#!/bin/sh
set -xe
mkdir /scratch && cd /scratch
{
  tar xzv --strip-components=1
  cp /etc/cabal.project.freeze .
  chmod +x striptests && ./striptests
  mkdir "$TARGETNAME"
  # This script does not cabal update because compiling anything new is slow
  ( IFS=';'; cabal build $CABALOPTS --enable-executable-static )
  find . -name shellcheck -type f -exec mv {} "$TARGETNAME/" \;
  ls -l "$TARGETNAME"
  strip -s "$TARGETNAME/shellcheck"
  ls -l "$TARGETNAME"
  "$TARGETNAME/shellcheck" --version
} >&2
tar czv "$TARGETNAME"


================================================
FILE: builders/linux.armv6hf/scutil
================================================
#!/bin/dash
# Various ShellCheck build utility functions

# Generally set a ulimit to avoid QEmu using too much memory
ulimit -v "$((10*1024*1024))"
# If we happen to invoke or run under QEmu, make sure to follow execve.
# This requires a patched QEmu.
export QEMU_EXECVE=1

# Retry a command until it succeeds
# Usage: scutil retry 3 mycmd
retry() {
  n="$1"
  ret=1
  shift
  while [ "$n" -gt 0 ]
  do
    "$@"
    ret=$?
    [ "$ret" = 0 ] && break
    n=$((n-1))
  done
  return "$ret"
}

# Install all dependencies from a freeze file
# Usage: scutil install_from_freeze /path/cabal.project.freeze cabal install
install_from_freeze() {
  linefeed=$(printf '\nx')
  linefeed=${linefeed%x}
  flags=$(
    sed 's/constraints:/&\n /' "$1" |
    grep -vw -e rts -e base -e ghc |
    sed -n -e 's/^  *\([^,]*\).*/\1/p' |
    sed -e 's/any\.\([^ ]*\) ==\(.*\)/\1-\2/; te; s/.*/--constraint\n&/; :e')
  shift
  # shellcheck disable=SC2086
  ( IFS=$linefeed; set -x; "$@" $flags )
}

# Run a command under emulation.
# This assumes the correct emulator is named 'qemu' and the chroot is /chroot
# Usage: scutil emu echo "Hello World"
emu() {
  chroot /chroot /bin/qemu /usr/bin/env "$@"
}

"$@"


================================================
FILE: builders/linux.armv6hf/tag
================================================
koalaman/scbuilder-linux-armv6hf


================================================
FILE: builders/linux.riscv64/Dockerfile
================================================
FROM ubuntu:25.04

ENV TARGETNAME=linux.riscv64
ENV TARGET=riscv64-linux-gnu

# Build dependencies
USER root
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y llvm-20 "gcc-$TARGET" "g++-$TARGET" ghc alex happy automake autoconf build-essential curl qemu-user-static
RUN curl -L "https://downloads.haskell.org/~cabal/cabal-install-3.16.0.0/cabal-install-3.16.0.0-x86_64-linux-alpine3_20.tar.xz" | tar xJv -C /usr/local/bin && cabal update

# Build GHC
WORKDIR /ghc
RUN curl -L "https://downloads.haskell.org/~ghc/9.12.2/ghc-9.12.2-src.tar.xz" | tar xJ --strip-components=1
RUN ./boot.source && ./configure --host x86_64-linux-gnu --build x86_64-linux-gnu --target "$TARGET"
# GHC fails to build if it can't encode non-ascii
ENV LC_CTYPE=C.utf8
# We have to do a binary-dist instead of a direct install, otherwise the targest won't have
# cross compilation prefixes in /usr/local/lib/aarch64-linux-gnu-ghc-*/lib/settings
RUN ./hadrian/build --flavour=quickest --bignum=native -V -j --prefix=/usr/local install
# Hadrian just outputs "gcc" as the name of gcc, without accounting for $TARGET. Manually fix up the paths:
RUN sed -e 's/"\(gcc\|g++\|ld\)"/"'"$TARGET"'-\1"/g' -i /usr/local/lib/$TARGET-ghc-*/lib/settings

# Due to an apparent cabal bug, we specify our options directly to cabal
# It won't reuse caches if ghc-options are specified in ~/.cabal/config
ENV CABALOPTS="--ghc-options;-split-sections -optc-Os -optc-Wl,--gc-sections -optc-fPIC;--with-compiler=$TARGET-ghc;--with-hc-pkg=$TARGET-ghc-pkg;-c;hashable -arch-native"

# Prebuild the dependencies
RUN cabal update && IFS=';' && cabal install --dependencies-only $CABALOPTS ShellCheck

# Copy the build script
COPY build /usr/bin

WORKDIR /scratch
ENTRYPOINT ["/usr/bin/build"]


================================================
FILE: builders/linux.riscv64/build
================================================
#!/bin/sh
set -xe
{
  tar xzv --strip-components=1
  chmod +x striptests && ./striptests
  mkdir "$TARGETNAME"
  ( IFS=';'; cabal build $CABALOPTS --enable-executable-static )
  find . -name shellcheck -type f -exec mv {} "$TARGETNAME/" \;
  ls -l "$TARGETNAME"
  "$TARGET-strip" -s "$TARGETNAME/shellcheck"
  ls -l "$TARGETNAME"
  "qemu-${TARGET%%-*}-static" "$TARGETNAME/shellcheck" --version
} >&2
tar czv "$TARGETNAME"


================================================
FILE: builders/linux.riscv64/tag
================================================
koalaman/scbuilder-linux-riscv64


================================================
FILE: builders/linux.x86_64/Dockerfile
================================================
FROM alpine:3.22
# alpine:3.16 (GHC 9.0.1):  5.8 megabytes (certs expired)
# alpine:3.17 (GHC 9.0.2): 15.0 megabytes (certs expired)
# alpine:3.18 (GHC 9.4.4): 29.0 megabytes (certs expired)
# alpine:3.19 (GHC 9.4.7): 29.0 megabytes (certs expired)
# alpine:3.20 (GHC 9.8.2): 16.0 megabytes
# alpine:3.21 (GHC 9.8.2): 16.0 megabytes
# alpine:3.22 (GHC 9.8.2): 16.0 megabytes

ENV TARGETNAME=linux.x86_64

# Install GHC and cabal
USER root
RUN apk add ghc cabal g++ libffi-dev curl bash gmp gmp-static

# Cabal has failed to cache if options are not specified on the command line,
# so do that explicitly.
ENV CABALOPTS="--ghc-options;-split-sections -optc-Os -optc-Wl,--gc-sections"

# Verify that we have the certificates in place to successfully update cabal
RUN cabal update && rm -rf ~/.cabal

# Other archs pre-build dependencies here, but this one doesn't to detect ecosystem movement
RUN true

# Copy the build script
COPY build /usr/bin

WORKDIR /scratch
ENTRYPOINT ["/usr/bin/build"]


================================================
FILE: builders/linux.x86_64/build
================================================
#!/bin/sh
set -xe
{
  tar xzv --strip-components=1
  chmod +x striptests && ./striptests
  mkdir "$TARGETNAME"
  cabal update
  ( IFS=';'; cabal build $CABALOPTS --enable-executable-static )
  find . -name shellcheck -type f -exec mv {} "$TARGETNAME/" \;
  ls -l "$TARGETNAME"
  strip -s "$TARGETNAME/shellcheck"
  ls -l "$TARGETNAME"
  "$TARGETNAME/shellcheck" --version
} >&2
tar czv "$TARGETNAME"


================================================
FILE: builders/linux.x86_64/tag
================================================
koalaman/scbuilder-linux-x86_64


================================================
FILE: builders/run_builder
================================================
#!/bin/bash
if [ $# -lt 2 ]
then
  echo >&2 "This script builds a source archive (as produced by cabal sdist)"
  echo >&2 "Usage: $0 sourcefile.tar.gz builddir..."
  exit 1
fi

file=$(realpath "$1")
shift

if [ ! -e "$file" ]
then
  echo >&2 "$file does not exist"
  exit 1
fi

set -ex -o pipefail

for dir
do
  tagfile="$dir/tag"
  if [ ! -e "$tagfile" ]
  then
    echo >&2 "$tagfile does not exist"
    exit 2
  fi

  docker run -i "$(< "$tagfile")" < "$file" | tar xz
done


================================================
FILE: builders/windows.x86_64/Dockerfile
================================================
FROM ubuntu:25.04

ENV TARGETNAME=windows.x86_64

# We don't need wine32, even though it complains
USER root
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y curl busybox wine winbind xz-utils

# Fetch Windows version, will be available under z:\haskell
WORKDIR /haskell
# 9.12.2 produces a 37M binary
# 9.0.2  produces a 28M binary
# 8.10.4 produces a 16M binary
# We don't want to be stuck on old versions forever though, so just go with the latest version
RUN curl -L "https://downloads.haskell.org/~ghc/9.12.2/ghc-9.12.2-x86_64-unknown-mingw32.tar.xz" | tar xJ --strip-components=1

# Fetch dependencies
WORKDIR /haskell/bin
RUN curl -L "https://downloads.haskell.org/~cabal/cabal-install-3.16.0.0/cabal-install-3.16.0.0-x86_64-windows.zip" | busybox unzip -
RUN curl -L "https://curl.se/windows/dl-8.15.0_2/curl-8.15.0_2-win64-mingw.zip" | busybox unzip - && mv curl-*-win64-mingw/bin/* .
RUN wine /haskell/bin/cabal.exe update
ENV WINEPATH=/haskell/bin:/haskell/mingw/bin

# None of these actually seem to have an effect on GHC on Windows anymore,
# but we'll leave them in place anyways.
ENV CABALOPTS="--ghc-options;-split-sections -optc-Os -optc-Wl,--gc-sections"

# Precompile some deps to speed up later builds
RUN IFS=';' && wine /haskell/bin/cabal.exe install --lib --dependencies-only $CABALOPTS ShellCheck

COPY build /usr/bin
WORKDIR /scratch
ENTRYPOINT ["/usr/bin/build"]


================================================
FILE: builders/windows.x86_64/build
================================================
#!/bin/sh
cabal() {
  wine /haskell/bin/cabal.exe  "$@"
}

set -xe
{
  tar xzv --strip-components=1
  chmod +x striptests && ./striptests
  mkdir "$TARGETNAME"
  ( IFS=';'; cabal build $CABALOPTS )
  find dist*/ -name shellcheck.exe -type f -ls -exec mv {} "$TARGETNAME/" \;
  ls -l "$TARGETNAME"
  wine "/haskell/mingw/bin/strip.exe" -s "$TARGETNAME/shellcheck.exe"
  ls -l "$TARGETNAME"
  wine "$TARGETNAME/shellcheck.exe" --version
} >&2
tar czv "$TARGETNAME"


================================================
FILE: builders/windows.x86_64/tag
================================================
koalaman/scbuilder-windows-x86_64


================================================
FILE: manpage
================================================
#!/bin/sh
echo >&2 "Generating man page using pandoc"
pandoc -s -f markdown-smart -t man shellcheck.1.md -o shellcheck.1 || exit
echo >&2 "Done. You can read it with:   man ./shellcheck.1"


================================================
FILE: nextnumber
================================================
#!/usr/bin/env bash
# TODO: Find a less trashy way to get the next available error code
if ! shopt -s globstar
then
  echo "Error: This script depends on Bash 4." >&2
  exit 1
fi

for i in 1 2 3
do
  last=$(grep -hv "^prop" ./**/*.hs | grep -Ewo "${i}[0-9]{3}" | sort -n | tail -n 1)
  echo "Next ${i}xxx: $((last+1))"
done


================================================
FILE: quickrun
================================================
#!/usr/bin/env bash
# quickrun runs ShellCheck in an interpreted mode.
# This allows testing changes without recompiling.

path=$(find . -type f -path './dist*/Paths_ShellCheck.hs' | sort | head -n 1)
if [ -z "$path" ]
then
  echo >&2 "Unable to find Paths_ShellCheck.hs. Please 'cabal build' once."
  exit 1
fi
path="${path%/*}"

exec runghc -isrc -i"$path" shellcheck.hs "$@"


================================================
FILE: quicktest
================================================
#!/usr/bin/env bash
# quicktest runs the ShellCheck unit tests in an interpreted mode.
# This allows running tests without compiling, which can be faster.
# 'cabal test' remains the source of truth.

path=$(find . -type f -path './dist*/Paths_ShellCheck.hs' | sort | head -n 1)
if [ -z "$path" ]
then
    echo >&2 "Unable to find Paths_ShellCheck.hs. Please 'cabal build' once."
      exit 1
fi
path="${path%/*}"


(
var=$(echo 'main' | ghci -isrc -i"$path" test/shellcheck.hs 2>&1 | tee /dev/stderr)
if [[ $var == *ExitSuccess* ]]
then
  exit 0
else
  grep -C 3 -e "Fail" -e "Tracing" <<< "$var"
  exit 1
fi
) 2>&1


================================================
FILE: setgitversion
================================================
#!/bin/sh -xe
# This script hardcodes the `git describe` version as ShellCheck's version number.
# This is done to allow shellcheck --version to differ from the cabal version when
# building git snapshots.

file="src/ShellCheck/Data.hs"
test -e "$file"
tmp=$(mktemp)
version=$(git describe)
sed -e "s/=.*VERSIONSTRING.*/= \"$version\" -- VERSIONSTRING, DO NOT SUBMIT/" "$file" > "$tmp"
mv "$tmp" "$file"


================================================
FILE: shellcheck.1.md
================================================
% SHELLCHECK(1) Shell script analysis tool

# NAME

shellcheck - Shell script analysis tool

# SYNOPSIS

**shellcheck** [*OPTIONS*...] *FILES*...

# DESCRIPTION

ShellCheck is a static analysis and linting tool for sh/bash scripts. It's
mainly focused on handling typical beginner and intermediate level syntax
errors and pitfalls where the shell just gives a cryptic error message or
strange behavior, but it also reports on a few more advanced issues where
corner cases can cause delayed failures.

ShellCheck gives shell specific advice. Consider this line:

    (( area = 3.14*r*r ))

+ For scripts starting with `#!/bin/sh` (or when using `-s sh`), ShellCheck
will warn that `(( .. ))` is not POSIX compliant (similar to checkbashisms).

+ For scripts starting with `#!/bin/bash` (or using `-s bash`), ShellCheck
will warn that decimals are not supported.

+ For scripts starting with `#!/bin/ksh` (or using `-s ksh`), ShellCheck will
not warn at all, as `ksh` supports decimals in arithmetic contexts.

# OPTIONS

**-a**,\ **--check-sourced**

:   Emit warnings in sourced files. Normally, `shellcheck` will only warn
    about issues in the specified files. With this option, any issues in
    sourced files will also be reported.

**-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**.

**-i**\ *CODE1*[,*CODE2*...],\ **--include=***CODE1*[,*CODE2*...]

:   Explicitly include only the specified codes in the report. Subsequent **-i**
    options are cumulative, but all the codes can be specified at once,
    comma-separated as a single argument. Include options override any provided
    exclude options.

**-e**\ *CODE1*[,*CODE2*...],\ **--exclude=***CODE1*[,*CODE2*...]

:   Explicitly exclude the specified codes from the report. Subsequent **-e**
    options are cumulative, but all the codes can be specified at once,
    comma-separated as a single argument.

**--extended-analysis=true/false**

:   Enable/disable Dataflow Analysis to identify more issues (default true). 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.

**-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.

**--list-optional**

:   Output a list of known optional checks. These can be enabled with **-o**
    flags or **enable** directives.

**--norc**

:   Don't try to look for .shellcheckrc configuration files.

**--rcfile** *RCFILE*

:   Prefer the specified configuration file over searching for one
    in the default locations.

**-o**\ *NAME1*[,*NAME2*...],\ **--enable=***NAME1*[,*NAME2*...]

:   Enable optional checks. The special name *all* enables all of them.
    Subsequent **-o** options accumulate. This is equivalent to specifying
    **enable** directives.

**-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`
    directives.

**-s**\ *shell*,\ **--shell=***shell*

:   Specify Bourne shell dialect. Valid values are *sh*, *bash*, *dash*, *ksh*,
    and *busybox*.
    The default is to deduce the shell from the file's `shell` directive,
    shebang, or `.bash/.bats/.dash/.ksh` extension, in that order. *sh* refers to
    POSIX `sh` (not the system's), and will warn of portability issues.

**-S**\ *SEVERITY*,\ **--severity=***severity*

:   Specify minimum severity of errors to consider. Valid values in order of
    severity are *error*, *warning*, *info* and *style*.
    The default is *style*.

**-V**,\ **--version**

:   Print version information and exit.

**-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.

**-x**,\ **--external-sources**

:   Follow `source` statements even when the file is not specified as input.
    By default, `shellcheck` will only follow files specified on the command
    line (plus `/dev/null`). This option allows following any file the script
    may `source`.

    This option may also be enabled using `external-sources=true` in
    `.shellcheckrc`. This flag takes precedence.

**FILES...**

:   One or more script files to check, or "-" for standard input.


# FORMATS

**tty**

:   Plain text, human readable output. This is the default.

**gcc**

:   GCC compatible output. Useful for editors that support compiling and
    showing syntax errors.

    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>

**checkstyle**

:   Checkstyle compatible XML output. Supported directly or through plugins
    by many IDEs and build monitoring systems.

        <?xml version='1.0' encoding='UTF-8'?>
        <checkstyle version='4.3'>
          <file name='file'>
            <error
              line='line'
              column='column'
              severity='severity'
              message='message'
              source='ShellCheck.SC####' />
            ...
          </file>
          ...
        </checkstyle>

**diff**

:   Auto-fixes in unified diff format. Can be piped to `git apply` or `patch -p1`
    to automatically apply fixes.

        --- a/test.sh
        +++ b/test.sh
        @@ -2,6 +2,6 @@
         ## Example of a broken script.
         for f in $(ls *.m3u)
         do
        -  grep -qi hq.*mp3 $f \
        +  grep -qi hq.*mp3 "$f" \
             && 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
    applications. ShellCheck's json is compact and contains only the bare
    minimum.  Tabs are counted as 1 character.

        {
          comments: [
            {
              "file": "filename",
              "line": lineNumber,
              "column": columnNumber,
              "level": "severitylevel",
              "code": errorCode,
              "message": "warning message"
            },
            ...
          ]
        }

**json**

:   This is a legacy version of the **json1** format. It's a raw array of
    comments, and all offsets have a tab stop of 8.

**quiet**

:   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.
If they appear before the first command, they are considered file-wide.
Otherwise, they apply to the immediately following command or block:

    # shellcheck key=value key=value
    command-or-structure

For example, to suppress SC2035 about using `./*.jpg`:

    # shellcheck disable=SC2035
    echo "Files: " *.jpg

To tell ShellCheck where to look for an otherwise dynamically determined file:

    # shellcheck source=./lib.sh
    source "$(find_install_dir)/lib.sh"

Here a shell brace group is used to suppress a warning on multiple lines:

    # shellcheck disable=SC2016
    {
      echo 'Modifying $PATH'
      echo 'PATH=foo:$PATH' >> ~/.bashrc
    }

Valid keys are:

**disable**
:   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.
    All warnings can be disabled with `disable=all`.

**enable**
:   Enable an optional check by name, as listed with **--list-optional**.
    Only file-wide `enable` directives are considered.

**extended-analysis**
:   Set to true/false to enable/disable dataflow analysis. Specifying
    `# shellcheck extended-analysis=false` 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.

**external-sources**
:   Set to `true` in `.shellcheckrc` to always allow ShellCheck to open
    arbitrary files from 'source' statements (the way most tools do).

    This option defaults to `false` only due to ShellCheck's origin as a
    remote service for checking untrusted scripts. It can safely be enabled
    for normal development.

**source**
:   Overrides the filename included by a `source`/`.` statement. This can be
    used to tell shellcheck where to look for a file whose name is determined
    at runtime, or to skip a source by telling it to use `/dev/null`.

**source-path**
:   Add a directory to the search path for `source`/`.` statements (by default,
    only ShellCheck's working directory is included). Absolute paths will also
    be rooted in these paths. The special path `SCRIPTDIR` can be used to
    specify the currently checked script's directory, as in
    `source-path=SCRIPTDIR` or `source-path=SCRIPTDIR/../libs`. Multiple
    paths accumulate, and `-P` takes precedence over them.

**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'.

# RC FILES

Unless `--norc` is used, ShellCheck will look for a file `.shellcheckrc` or
`shellcheckrc` in the script's directory and each parent directory. If found,
it will read `key=value` pairs from it and treat them as file-wide directives.

Here is an example `.shellcheckrc`:

    # Look for 'source'd files relative to the checked script,
    # and also look for absolute paths in /mnt/chroot
    source-path=SCRIPTDIR
    source-path=/mnt/chroot

    # Since 0.9.0, values can be quoted with '' or "" to allow spaces
    source-path="My Documents/scripts"

    # Allow opening any 'source'd file, even if not specified as input
    external-sources=true

    # Turn on warnings for unquoted variables with safe values
    enable=quote-safe-variables

    # Turn on warnings for unassigned uppercase variables
    enable=check-unassigned-uppercase

    # Allow [ ! -z foo ] instead of suggesting -n
    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.

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.


# ENVIRONMENT VARIABLES

The environment variable `SHELLCHECK_OPTS` can be set with default flags:

    export SHELLCHECK_OPTS='--shell=bash --exclude=SC2016'

Its value will be split on spaces and prepended to the command line on each
invocation.

# RETURN VALUES

ShellCheck uses the following exit codes:

+ 0: All files successfully scanned with no issues.
+ 1: All files successfully scanned with some issues.
+ 2: Some files could not be processed (e.g. file not found).
+ 3: ShellCheck was invoked with bad syntax (e.g. unknown flag).
+ 4: ShellCheck was invoked with bad options (e.g. unknown formatter).

# LOCALE

This version of ShellCheck is only available in English. All files are
leniently decoded as UTF-8, with a fallback of ISO-8859-1 for invalid
sequences. `LC_CTYPE` is respected for output, and defaults to UTF-8 for
locales where encoding is unspecified (such as the `C` locale).

Windows users seeing `commitBuffer: invalid argument (invalid character)`
should set their terminal to use UTF-8 with `chcp 65001`.

# KNOWN INCOMPATIBILITIES

(If nothing in this section makes sense, you are unlikely to be affected by it)

To avoid confusing and misguided suggestions, ShellCheck requires function
bodies to be either `{ brace groups; }` or `( subshells )`, and function names
containing `[]*=!` are only recognized after a `function` keyword.

The following unconventional function definitions are identical in Bash,
but ShellCheck only recognizes the latter.

    [x!=y] () [[ $1 ]]
    function [x!=y] () { [[ $1 ]]; }

Shells without the `function` keyword do not allow these characters in function
names to begin with.  Function names containing `{}` are not supported at all.

Further, if ShellCheck sees `[x!=y]` it will assume this is an invalid
comparison. To invoke the above function, quote the command as in `'[x!=y]'`,
or to retain the same globbing behavior, use `command [x!=y]`.

ShellCheck imposes additional restrictions on the `[` command to help diagnose
common invalid uses. While `[ $x= 1 ]` is defined in POSIX, ShellCheck will
assume it was intended as the much more likely comparison `[ "$x" = 1 ]` and
fail accordingly. For unconventional or dynamic uses of the `[` command, use
`test` or `\[` instead.

# REPORTING BUGS

Bugs and issues can be reported on GitHub:

https://github.com/koalaman/shellcheck/issues

# AUTHORS

ShellCheck is developed and maintained by Vidar Holen, with assistance from a
long list of wonderful contributors.

# COPYRIGHT

Copyright 2012-2025, Vidar Holen and contributors.
Licensed under the GNU General Public License version 3 or later,
see https://gnu.org/licenses/gpl.html

# SEE ALSO

sh(1), bash(1), dash(1), ksh(1)


================================================
FILE: shellcheck.hs
================================================
{-
    Copyright 2012-2019 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/>.
-}
import qualified ShellCheck.Analyzer
import           ShellCheck.Checker
import           ShellCheck.Data
import           ShellCheck.Interface
import           ShellCheck.Regex

import qualified ShellCheck.Formatter.CheckStyle
import           ShellCheck.Formatter.Format
import qualified ShellCheck.Formatter.Diff
import qualified ShellCheck.Formatter.GCC
import qualified ShellCheck.Formatter.JSON
import qualified ShellCheck.Formatter.JSON1
import qualified ShellCheck.Formatter.TTY
import qualified ShellCheck.Formatter.Quiet

import           Control.Exception
import           Control.Monad
import           Control.Monad.IO.Class
import           Control.Monad.Trans.Class
import           Control.Monad.Except
import           Data.Bits
import           Data.Char
import           Data.Either
import           Data.Functor
import           Data.IORef
import           Data.List
import qualified Data.Map                        as Map
import           Data.Maybe
import           Data.Monoid
import           Data.Semigroup                  (Semigroup (..))
import           Prelude                         hiding (catch)
import           System.Console.GetOpt
import           System.Directory
import           System.Environment
import           System.Exit
import           System.FilePath
import           System.IO

data Flag = Flag String String
data Status =
    NoProblems
    | SomeProblems
    | SupportFailure
    | SyntaxFailure
    | RuntimeException
  deriving (Ord, Eq, Show)

instance Semigroup Status where
    (<>) = max

instance Monoid Status where
    mempty = NoProblems
    mappend = (Data.Semigroup.<>)

data Options = Options {
    checkSpec        :: CheckSpec,
    externalSources  :: Bool,
    sourcePaths      :: [FilePath],
    formatterOptions :: FormatterOptions,
    minSeverity      :: Severity,
    rcfile           :: Maybe FilePath
}

defaultOptions = Options {
    checkSpec = emptyCheckSpec,
    externalSources = False,
    sourcePaths = [],
    formatterOptions = newFormatterOptions {
        foColorOption = ColorAuto
    },
    minSeverity = StyleC,
    rcfile = Nothing
}

usageHeader = "Usage: shellcheck [OPTIONS...] FILES..."
options = [
    Option "a" ["check-sourced"]
        (NoArg $ Flag "sourced" "false") "Include warnings from sourced files",
    Option "C" ["color"]
        (OptArg (maybe (Flag "color" "always") (Flag "color")) "WHEN")
        "Use color (auto, always, never)",
    Option "i" ["include"]
        (ReqArg (Flag "include") "CODE1,CODE2..") "Consider only given types of warnings",
    Option "e" ["exclude"]
        (ReqArg (Flag "exclude") "CODE1,CODE2..") "Exclude types of warnings",
    Option "" ["extended-analysis"]
        (ReqArg (Flag "extended-analysis") "bool") "Perform dataflow analysis (default true)",
    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",
    Option "" ["rcfile"]
        (ReqArg (Flag "rcfile") "RCFILE")
        "Prefer the specified configuration file over searching for one",
    Option "o" ["enable"]
        (ReqArg (Flag "enable") "check1,check2..")
        "List of optional checks to enable (or 'all')",
    Option "P" ["source-path"]
        (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)",
    Option "S" ["severity"]
        (ReqArg (Flag "severity") "SEVERITY")
        "Minimum severity of errors to consider (error, warning, info, style)",
    Option "V" ["version"]
        (NoArg $ Flag "version" "true") "Print version information",
    Option "W" ["wiki-link-count"]
        (ReqArg (Flag "wiki-link-count") "NUM")
        "The number of wiki links to show, when applicable",
    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"
    ]
getUsageInfo = usageInfo usageHeader options

printErr = lift . hPutStrLn stderr

parseArguments :: [String] -> ExceptT Status IO ([Flag], [FilePath])
parseArguments argv =
    case getOpt Permute options argv of
        (opts, files, []) -> return (opts, files)
        (_, _, errors) -> do
            printErr $ concat errors ++ "\n" ++ getUsageInfo
            throwError SyntaxFailure

formats :: FormatterOptions -> Map.Map String (IO Formatter)
formats options = Map.fromList [
    ("checkstyle", ShellCheck.Formatter.CheckStyle.format),
    ("diff",  ShellCheck.Formatter.Diff.format options),
    ("gcc",  ShellCheck.Formatter.GCC.format),
    ("json", ShellCheck.Formatter.JSON.format),
    ("json1", ShellCheck.Formatter.JSON1.format),
    ("tty",  ShellCheck.Formatter.TTY.format options),
    ("quiet",  ShellCheck.Formatter.Quiet.format options)
    ]

formatList = intercalate ", " names
  where
    names = Map.keys $ formats (formatterOptions defaultOptions)

getOption [] _                  = Nothing
getOption (Flag var val:_) name | name == var = return val
getOption (_:rest) flag         = getOption rest flag

getOptions options name =
    map (\(Flag _ val) -> val) . filter (\(Flag var _) -> var == name) $ options

split char str =
    split' str []
  where
    split' (a:rest) element =
        if a == char
        then reverse element : split' rest []
        else split' rest (a:element)
    split' [] element = [reverse element]

toStatus = fmap (either id id) . runExceptT

getEnvArgs = do
    opts <- getEnv "SHELLCHECK_OPTS" `catch` cantWaitForLookupEnv
    return . filter (not . null) $ opts `splitOn` mkRegex " +"
  where
    cantWaitForLookupEnv :: IOException -> IO String
    cantWaitForLookupEnv = const $ return ""

main = do
    params <- getArgs
    envOpts  <- getEnvArgs
    let args = envOpts ++ params
    status <- toStatus $ do
        (flags, files) <- parseArguments args
        process flags files
    exitWith $ statusToCode status

statusToCode status =
    case status of
        NoProblems       -> ExitSuccess
        SomeProblems     -> ExitFailure 1
        SyntaxFailure    -> ExitFailure 3
        SupportFailure   -> ExitFailure 4
        RuntimeException -> ExitFailure 2

process :: [Flag] -> [FilePath] -> ExceptT Status IO Status
process flags files = do
    options <- foldM (flip parseOption) defaultOptions flags
    verifyFiles files
    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

runFormatter :: SystemInterface IO -> Formatter -> Options -> [FilePath]
            -> IO Status
runFormatter sys format options files = do
    header format
    result <- foldM f NoProblems files
    footer format
    return result
  where
    f :: Status -> FilePath -> IO Status
    f status file = do
        newStatus <- process file `catch` handler file
        return $! status `mappend` newStatus
    handler :: FilePath -> IOException -> IO Status
    handler file e = reportFailure file (show e)
    reportFailure file str = do
        onFailure format file str
        return RuntimeException

    process :: FilePath -> IO Status
    process filename = do
        input <- siReadFile sys Nothing filename
        either (reportFailure filename) check input
      where
        check contents = do
            let checkspec = (checkSpec options) {
                csFilename = filename,
                csScript = contents
            }
            result <- checkScript sys checkspec
            onResult format result sys
            return $
                if null (crComments result)
                then NoProblems
                else SomeProblems

parseEnum name value list =
    case lookup value list of
        Just value -> return value
        Nothing -> do
            printErr $ "Unknown value for --" ++ name ++ ". " ++
                       "Valid options are: " ++ (intercalate ", " $ map fst list)
            throwError SupportFailure

parseColorOption value =
    parseEnum "color" value [
        ("auto",   ColorAuto),
        ("always", ColorAlways),
        ("never",  ColorNever)
        ]

parseSeverityOption value =
    parseEnum "severity" value [
        ("error",   ErrorC),
        ("warning", WarningC),
        ("info",    InfoC),
        ("style",   StyleC)
        ]

parseOption flag options =
    case flag of
        Flag "shell" str ->
            fromMaybe (die $ "Unknown shell: " ++ str) $ do
                shell <- shellForExecutable str
                return $ return options {
                            checkSpec = (checkSpec options) {
                                csShellTypeOverride = Just shell
                            }
                        }

        Flag "exclude" str -> do
            new <- mapM parseNum $ filter (not . null) $ split ',' str
            let old = csExcludedWarnings . checkSpec $ options
            return options {
                checkSpec = (checkSpec options) {
                    csExcludedWarnings = new ++ old
                }
            }

        Flag "include" str -> do
            new <- mapM parseNum $ filter (not . null) $ split ',' str
            let old = csIncludedWarnings . checkSpec $ options
            return options {
                checkSpec = (checkSpec options) {
                    csIncludedWarnings =
                      if null new
                        then old
                        else Just new `mappend` old
                }
            }

        Flag "version" _ -> do
            liftIO printVersion
            throwError NoProblems

        Flag "list-optional" _ -> do
            liftIO printOptional
            throwError NoProblems

        Flag "help" _ -> do
            liftIO $ putStrLn getUsageInfo
            throwError NoProblems

        Flag "externals" _ ->
            return options {
                externalSources = True
            }

        Flag "color" color -> do
            option <- parseColorOption color
            return options {
                formatterOptions = (formatterOptions options) {
                    foColorOption = option
                }
            }

        Flag "source-path" str -> do
            let paths = splitSearchPath str
            return options {
                sourcePaths = (sourcePaths options) ++ paths
            }

        Flag "sourced" _ ->
            return options {
                checkSpec = (checkSpec options) {
                    csCheckSourced = True
                }
            }

        Flag "severity" severity -> do
            option <- parseSeverityOption severity
            return options {
                checkSpec = (checkSpec options) {
                    csMinSeverity = option
                }
            }

        Flag "wiki-link-count" countString -> do
            count <- parseNum countString
            return options {
                formatterOptions = (formatterOptions options) {
                    foWikiLinkCount = count
                }
            }

        Flag "norc" _ ->
            return options {
                checkSpec = (checkSpec options) {
                    csIgnoreRC = True
                }
            }

        Flag "rcfile" str -> do
            return options {
                rcfile = Just str
            }

        Flag "enable" value ->
            let cs = checkSpec options in return options {
                checkSpec = cs {
                    csOptionalChecks = (csOptionalChecks cs) ++ split ',' value
                }
            }

        Flag "extended-analysis" str -> do
            value <- parseBool str
            return options {
                checkSpec = (checkSpec options) {
                    csExtendedAnalysis = Just value
                }
            }

        -- This flag is handled specially in 'process'
        Flag "format" _ -> return options

        Flag str _ -> do
            printErr $ "Internal error for --" ++ str ++ ". Please file a bug :("
            return options
  where
    die s = do
        printErr s
        throwError SupportFailure
    parseNum ('S':'C':str) = parseNum str
    parseNum num = do
        unless (all isDigit num) $ do
            printErr $ "Invalid number: " ++ num
            throwError SyntaxFailure
        return (Prelude.read num :: Integer)

    parseBool str = do
        case str of
            "true" -> return True
            "false" -> return False
            _ -> do
                printErr $ "Invalid boolean, expected true/false: " ++ str
                throwError SyntaxFailure

ioInterface :: Options -> [FilePath] -> IO (SystemInterface IO)
ioInterface options files = do
    inputs <- mapM normalize files
    cache <- newIORef emptyCache
    configCache <- newIORef ("", Nothing)
    return (newSystemInterface :: SystemInterface IO) {
        siReadFile = get cache inputs,
        siFindSource = findSourceFile inputs (sourcePaths options),
        siGetConfig = getConfig configCache
    }
  where
    emptyCache :: Map.Map FilePath String
    emptyCache = Map.empty

    get cache inputs rcSuggestsExternal file = do
        map <- readIORef cache
        case Map.lookup file map of
            Just x  -> return $ Right x
            Nothing -> fetch cache inputs rcSuggestsExternal file

    fetch cache inputs rcSuggestsExternal file = do
        ok <- allowable rcSuggestsExternal inputs file
        if ok
          then (do
            (contents, shouldCache) <- inputFile file
            when shouldCache $
                modifyIORef cache $ Map.insert file contents
            return $ Right contents
            ) `catch` handler
          else
            if rcSuggestsExternal == Just False
            then return $ Left (file ++ " was not specified as input, and external files were disabled via directive.")
            else return $ Left (file ++ " was not specified as input (see shellcheck -x).")
      where
        handler :: IOException -> IO (Either ErrorMessage String)
        handler ex = return . Left $ show ex

    allowable rcSuggestsExternal inputs x =
        if fromMaybe (externalSources options) rcSuggestsExternal
        then return True
        else do
            path <- normalize x
            return $ path `elem` inputs

    normalize x =
        canonicalizePath x `catch` fallback x
      where
        fallback :: FilePath -> IOException -> IO FilePath
        fallback path _ = return path


    -- Returns the name and contents of .shellcheckrc for the given file
    getConfig cache filename =
        case rcfile options of
            Just file -> do
                -- We have a specified rcfile. Ignore normal rcfile resolution.
                (path, result) <- readIORef cache
                if path == "/"
                  then return result
                  else do
                    result <- readConfig file
                    when (isNothing result) $
                        hPutStrLn stderr $ "Warning: unable to read --rcfile " ++ file
                    writeIORef cache ("/", result)
                    return result

            Nothing -> do
                path <- normalize filename
                let dir = takeDirectory path
                (previousPath, result) <- readIORef cache
                if dir == previousPath
                  then return result
                  else do
                    paths <- getConfigPaths dir
                    result <- findConfig paths
                    writeIORef cache (dir, result)
                    return result

    findConfig paths =
        case paths of
            (file:rest) -> do
                contents <- readConfig file
                if isJust contents
                  then return contents
                  else findConfig rest
            [] -> return Nothing

    -- 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.
    getConfigPaths dir = do
        let next = takeDirectory dir
        rest <- if next /= dir
                then getConfigPaths next
                else defaultPaths `catch`
                        ((const $ return []) :: IOException -> IO [FilePath])
        return $ (dir </> ".shellcheckrc") : (dir </> "shellcheckrc") : rest

    defaultPaths = do
        home <- getAppUserDataDirectory "shellcheckrc"
        xdg <- getXdgDirectory XdgConfig "shellcheckrc"
        return [home, xdg]

    readConfig file = do
        exists <- doesFileExist file
        if exists
          then do
            (contents, _) <- inputFile file `catch` handler file
            return $ Just (file, contents)
          else
            return Nothing
      where
        handler :: FilePath -> IOException -> IO (String, Bool)
        handler file err = do
            hPutStrLn stderr $ file ++ ": " ++ show err
            return ("", True)

    andM a b arg = do
        first <- a arg
        if not first then return False else b arg

    findM p = foldr go (pure Nothing)
      where
        go x acc = do
            b <- p x
            if b then pure (Just x) else acc

    findSourceFile inputs sourcePathFlag currentScript rcSuggestsExternal sourcePathAnnotation original =
        if isAbsolute original
        then
            let (_, relative) = splitDrive original
            in find relative original
        else
            find original original
      where
        find filename deflt = do
            sources <- findM ((allowable rcSuggestsExternal inputs) `andM` doesFileExist) $
                        (adjustPath filename):(map ((</> filename) . adjustPath) $ sourcePathFlag ++ sourcePathAnnotation)
            case sources of
                Nothing -> return deflt
                Just first -> return first
        scriptdir = dropFileName currentScript
        adjustPath str =
            case (splitDirectories str) of
                ("SCRIPTDIR":rest) -> joinPath (scriptdir:rest)
                _ -> str

inputFile file = do
    (handle, shouldCache) <-
            if file == "-"
            then return (stdin, True)
            else do
                h <- openBinaryFile file ReadMode
                reopenable <- hIsSeekable h
                return (h, not reopenable)

    hSetBinaryMode handle True
    contents <- decodeString <$> hGetContents handle -- closes handle

    seq (length contents) $
        return (contents, shouldCache)

-- Decode a char8 string into a utf8 string, with fallback on
-- ISO-8859-1. This avoids depending on additional libraries.
decodeString = decode
  where
    decode [] = []
    decode (c:rest) | isAscii c = c : decode rest
    decode (c:rest) =
        let num = (fromIntegral $ ord c) :: Int
            next = case num of
                _ | num >= 0xF8 -> Nothing
                  | num >= 0xF0 -> construct (num .&. 0x07) 3 rest
                  | num >= 0xE0 -> construct (num .&. 0x0F) 2 rest
                  | num >= 0xC0 -> construct (num .&. 0x1F) 1 rest
                  | True -> Nothing
        in
            case next of
                Just (n, remainder) -> chr n : decode remainder
                Nothing             -> c : decode rest

    construct x 0 rest = do
        guard $ x <= 0x10FFFF
        return (x, rest)
    construct x n (c:rest) =
        let num = (fromIntegral $ ord c) :: Int in
            if num >= 0x80 && num <= 0xBF
            then construct ((x `shiftL` 6) .|. (num .&. 0x3f)) (n-1) rest
            else Nothing
    construct _ _ _ = Nothing


verifyFiles files =
    when (null files) $ do
        printErr "No files specified.\n"
        printErr $ usageInfo usageHeader options
        throwError SyntaxFailure

printVersion = do
    putStrLn   "ShellCheck - shell script analysis tool"
    putStrLn $ "version: " ++ shellcheckVersion
    putStrLn   "license: GNU General Public License, version 3"
    putStrLn   "website: https://www.shellcheck.net"

printOptional = do
    mapM f list
  where
    list = sortOn cdName ShellCheck.Analyzer.optionalChecks
    f item = do
        putStrLn $ "name:    " ++ cdName item
        putStrLn $ "desc:    " ++ cdDescription item
        putStrLn $ "example: " ++ cdPositive item
        putStrLn $ "fix:     " ++ cdNegative item
        putStrLn ""


================================================
FILE: snap/snapcraft.yaml
================================================
name: shellcheck
summary: A shell script static analysis tool
description: |
  ShellCheck is a GPLv3 tool that gives warnings and suggestions for bash/sh
  shell scripts.

  The goals of ShellCheck are

  - To point out and clarify typical beginner's syntax issues that cause a
    shell to give cryptic error messages.

  - To point out and clarify typical intermediate level semantic problems that
    cause a shell to behave strangely and counter-intuitively.

  - To point out subtle caveats, corner cases and pitfalls that may cause an
    advanced user's otherwise working script to fail under future
    circumstances.

  By default ShellCheck can only check non-hidden files under /home, to make
  ShellCheck be able to check files under /media and /run/media you must
  connect it to the `removable-media` interface manually:

      # snap connect shellcheck:removable-media

version: git
base: core24
grade: stable
confinement: strict

apps:
  shellcheck:
    command: usr/bin/shellcheck
    plugs: [home, removable-media]
    environment:
      LANG: C.UTF-8

parts:
  shellcheck:
    plugin: dump
    source: .
    build-packages:
      - cabal-install
    override-build: |
      # Give ourselves enough memory to build
      fallocate -l 2G /tmp/swap
      chmod 0600 /tmp/swap
      mkswap /tmp/swap
      if ! swapon /tmp/swap; then
        echo "Could not enable swap file, continuing anyway"
        rm /tmp/swap
      fi

      cabal update
      cabal install -j

      install -d "${CRAFT_PART_INSTALL}/usr/bin"
      install --strip ~/.cabal/bin/shellcheck "${CRAFT_PART_INSTALL}/usr/bin"


================================================
FILE: src/ShellCheck/AST.hs
================================================
{-
    Copyright 2012-2019 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 DeriveGeneric, DeriveAnyClass, DeriveTraversable, PatternSynonyms #-}
module ShellCheck.AST where

import GHC.Generics (Generic)
import Control.Monad.Identity
import Control.DeepSeq
import Text.Parsec
import qualified ShellCheck.Regex as Re
import Prelude hiding (id)

newtype Id = Id Int deriving (Show, Eq, Ord, Generic, NFData)

data Quoted = Quoted | Unquoted deriving (Show, Eq)
data Dashed = Dashed | Undashed deriving (Show, Eq)
data Piped = Piped | Unpiped deriving (Show, Eq)
data AssignmentMode = Assign | Append deriving (Show, Eq)
newtype FunctionKeyword = FunctionKeyword Bool deriving (Show, Eq)
newtype FunctionParentheses = FunctionParentheses Bool deriving (Show, Eq)
data CaseType = CaseBreak | CaseFallThrough | CaseContinue deriving (Show, Eq)

newtype Root = Root Token
data Token = OuterToken Id (InnerToken Token) deriving (Show)

data InnerToken t =
    Inner_TA_Binary String t t
    | Inner_TA_Assignment String t t
    | Inner_TA_Variable String [t]
    | Inner_TA_Expansion [t]
    | Inner_TA_Sequence [t]
    | Inner_TA_Parenthesis t
    | Inner_TA_Trinary t t t
    | Inner_TA_Unary String t
    | Inner_TC_And ConditionType String t t
    | Inner_TC_Binary ConditionType String t t
    | Inner_TC_Group ConditionType t
    | Inner_TC_Nullary ConditionType t
    | Inner_TC_Or ConditionType String t t
    | Inner_TC_Unary ConditionType String t
    | Inner_TC_Empty ConditionType
    | Inner_T_AND_IF
    | Inner_T_AndIf t t
    | Inner_T_Arithmetic t
    | Inner_T_Array [t]
    | Inner_T_IndexedElement [t] t
    -- Store the index as string, and parse as arithmetic or string later
    | Inner_T_UnparsedIndex SourcePos String
    | Inner_T_Assignment AssignmentMode String [t] t
    | Inner_T_Backgrounded t
    | Inner_T_Backticked [t]
    | Inner_T_Bang
    | Inner_T_Banged t
    | Inner_T_BraceExpansion [t]
    | Inner_T_BraceGroup [t]
    | Inner_T_CLOBBER
    | Inner_T_Case
    | Inner_T_CaseExpression t [(CaseType, [t], [t])]
    | Inner_T_Condition ConditionType t
    | Inner_T_DGREAT
    | Inner_T_DLESS
    | Inner_T_DLESSDASH
    | Inner_T_DSEMI
    | Inner_T_Do
    | Inner_T_DollarArithmetic t
    | Inner_T_DollarBraced Bool t
    | Inner_T_DollarBracket t
    | Inner_T_DollarDoubleQuoted [t]
    | Inner_T_DollarExpansion [t]
    | Inner_T_DollarSingleQuoted String
    | Inner_T_DollarBraceCommandExpansion Piped [t]
    | Inner_T_Done
    | Inner_T_DoubleQuoted [t]
    | Inner_T_EOF
    | Inner_T_Elif
    | Inner_T_Else
    | Inner_T_Esac
    | Inner_T_Extglob String [t]
    | Inner_T_FdRedirect String t
    | Inner_T_Fi
    | Inner_T_For
    | Inner_T_ForArithmetic t t t [t]
    | Inner_T_ForIn String [t] [t]
    | Inner_T_Function FunctionKeyword FunctionParentheses String t
    | Inner_T_GREATAND
    | Inner_T_Glob String
    | Inner_T_Greater
    | Inner_T_HereDoc Dashed Quoted String [t]
    | Inner_T_HereString t
    | Inner_T_If
    | Inner_T_IfExpression [([t],[t])] [t]
    | Inner_T_In
    | Inner_T_IoFile t t
    | Inner_T_IoDuplicate t String
    | Inner_T_LESSAND
    | Inner_T_LESSGREAT
    | Inner_T_Lbrace
    | Inner_T_Less
    | Inner_T_Literal String
    | Inner_T_Lparen
    | Inner_T_NEWLINE
    | Inner_T_NormalWord [t]
    | Inner_T_OR_IF
    | Inner_T_OrIf t t
    | Inner_T_ParamSubSpecialChar String -- e.g. '%' in ${foo%bar}  or '/' in ${foo/bar/baz}
    | Inner_T_Pipeline [t] [t] -- [Pipe separators] [Commands]
    | Inner_T_ProcSub String [t]
    | Inner_T_Rbrace
    | Inner_T_Redirecting [t] t
    | Inner_T_Rparen
    | Inner_T_Script t [t] -- Shebang T_Literal, followed by script.
    | Inner_T_Select
    | Inner_T_SelectIn String [t] [t]
    | Inner_T_Semi
    | Inner_T_SimpleCommand [t] [t]
    | Inner_T_SingleQuoted String
    | Inner_T_Subshell [t]
    | Inner_T_Then
    | Inner_T_Until
    | Inner_T_UntilExpression [t] [t]
    | Inner_T_While
    | Inner_T_WhileExpression [t] [t]
    | Inner_T_Annotation [Annotation] t
    | Inner_T_Pipe String
    | Inner_T_CoProc (Maybe Token) t
    | Inner_T_CoProcBody t
    | Inner_T_Include t
    | Inner_T_SourceCommand t t
    | Inner_T_BatsTest String t
    deriving (Show, Eq, Functor, Foldable, Traversable)

data Annotation =
    DisableComment Integer Integer -- [from, to)
    | EnableComment String
    | SourceOverride String
    | ShellOverride String
    | SourcePath String
    | ExternalSources Bool
    | ExtendedAnalysis Bool
    deriving (Show, Eq)
data ConditionType = DoubleBracket | SingleBracket deriving (Show, Eq)

pattern T_AND_IF id = OuterToken id Inner_T_AND_IF
pattern T_Bang id = OuterToken id Inner_T_Bang
pattern T_Case id = OuterToken id Inner_T_Case
pattern TC_Empty id typ = OuterToken id (Inner_TC_Empty typ)
pattern T_CLOBBER id = OuterToken id Inner_T_CLOBBER
pattern T_DGREAT id = OuterToken id Inner_T_DGREAT
pattern T_DLESS id = OuterToken id Inner_T_DLESS
pattern T_DLESSDASH id = OuterToken id Inner_T_DLESSDASH
pattern T_Do id = OuterToken id Inner_T_Do
pattern T_DollarSingleQuoted id str = OuterToken id (Inner_T_DollarSingleQuoted str)
pattern T_Done id = OuterToken id Inner_T_Done
pattern T_DSEMI id = OuterToken id Inner_T_DSEMI
pattern T_Elif id = OuterToken id Inner_T_Elif
pattern T_Else id = OuterToken id Inner_T_Else
pattern T_EOF id = OuterToken id Inner_T_EOF
pattern T_Esac id = OuterToken id Inner_T_Esac
pattern T_Fi id = OuterToken id Inner_T_Fi
pattern T_For id = OuterToken id Inner_T_For
pattern T_Glob id str = OuterToken id (Inner_T_Glob str)
pattern T_GREATAND id = OuterToken id Inner_T_GREATAND
pattern T_Greater id = OuterToken id Inner_T_Greater
pattern T_If id = OuterToken id Inner_T_If
pattern T_In id = OuterToken id Inner_T_In
pattern T_Lbrace id = OuterToken id Inner_T_Lbrace
pattern T_Less id = OuterToken id Inner_T_Less
pattern T_LESSAND id = OuterToken id Inner_T_LESSAND
pattern T_LESSGREAT id = OuterToken id Inner_T_LESSGREAT
pattern T_Literal id str = OuterToken id (Inner_T_Literal str)
pattern T_Lparen id = OuterToken id Inner_T_Lparen
pattern T_NEWLINE id = OuterToken id Inner_T_NEWLINE
pattern T_OR_IF id = OuterToken id Inner_T_OR_IF
pattern T_ParamSubSpecialChar id str = OuterToken id (Inner_T_ParamSubSpecialChar str)
pattern T_Pipe id str = OuterToken id (Inner_T_Pipe str)
pattern T_Rbrace id = OuterToken id Inner_T_Rbrace
pattern T_Rparen id = OuterToken id Inner_T_Rparen
pattern T_Select id = OuterToken id Inner_T_Select
pattern T_Semi id = OuterToken id Inner_T_Semi
pattern T_SingleQuoted id str = OuterToken id (Inner_T_SingleQuoted str)
pattern T_Then id = OuterToken id Inner_T_Then
pattern T_UnparsedIndex id pos str = OuterToken id (Inner_T_UnparsedIndex pos str)
pattern T_Until id = OuterToken id Inner_T_Until
pattern T_While id = OuterToken id Inner_T_While
pattern TA_Assignment id op t1 t2 = OuterToken id (Inner_TA_Assignment op t1 t2)
pattern TA_Binary id op t1 t2 = OuterToken id (Inner_TA_Binary op t1 t2)
pattern TA_Expansion id t = OuterToken id (Inner_TA_Expansion t)
pattern T_AndIf id t u = OuterToken id (Inner_T_AndIf t u)
pattern T_Annotation id anns t = OuterToken id (Inner_T_Annotation anns t)
pattern T_Arithmetic id c = OuterToken id (Inner_T_Arithmetic c)
pattern T_Array id t = OuterToken id (Inner_T_Array t)
pattern TA_Sequence id l = OuterToken id (Inner_TA_Sequence l)
pattern TA_Parenthesis id t = OuterToken id (Inner_TA_Parenthesis t)
pattern T_Assignment id mode var indices value = OuterToken id (Inner_T_Assignment mode var indices value)
pattern TA_Trinary id t1 t2 t3 = OuterToken id (Inner_TA_Trinary t1 t2 t3)
pattern TA_Unary id op t1 = OuterToken id (Inner_TA_Unary op t1)
pattern TA_Variable id str t = OuterToken id (Inner_TA_Variable str t)
pattern T_Backgrounded id l = OuterToken id (Inner_T_Backgrounded l)
pattern T_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)
pattern T_BraceExpansion id list = OuterToken id (Inner_T_BraceExpansion list)
pattern T_BraceGroup id l = OuterToken id (Inner_T_BraceGroup l)
pattern TC_And id typ str t1 t2 = OuterToken id (Inner_TC_And typ str t1 t2)
pattern T_CaseExpression id word cases = OuterToken id (Inner_T_CaseExpression word cases)
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_CoProcBody id t = OuterToken id (Inner_T_CoProcBody t)
pattern T_CoProc id var body = OuterToken id (Inner_T_CoProc var body)
pattern TC_Or id typ str t1 t2 = OuterToken id (Inner_TC_Or typ str t1 t2)
pattern TC_Unary id typ op token = OuterToken id (Inner_TC_Unary typ op token)
pattern T_DollarArithmetic id c = OuterToken id (Inner_T_DollarArithmetic c)
pattern T_DollarBraceCommandExpansion id pipe list = OuterToken id (Inner_T_DollarBraceCommandExpansion pipe list)
pattern T_DollarBraced id braced op = OuterToken id (Inner_T_DollarBraced braced op)
pattern T_DollarBracket id c = OuterToken id (Inner_T_DollarBracket c)
pattern T_DollarDoubleQuoted id list = OuterToken id (Inner_T_DollarDoubleQuoted list)
pattern T_DollarExpansion id list = OuterToken id (Inner_T_DollarExpansion list)
pattern T_DoubleQuoted id list = OuterToken id (Inner_T_DoubleQuoted list)
pattern T_Extglob id str l = OuterToken id (Inner_T_Extglob str l)
pattern T_FdRedirect id v t = OuterToken id (Inner_T_FdRedirect v t)
pattern T_ForArithmetic id a b c group = OuterToken id (Inner_T_ForArithmetic a b c group)
pattern T_ForIn id v w l = OuterToken id (Inner_T_ForIn v w l)
pattern T_Function id a b name body = OuterToken id (Inner_T_Function a b name body)
pattern T_HereDoc id d q str l = OuterToken id (Inner_T_HereDoc d q str l)
pattern T_HereString id word = OuterToken id (Inner_T_HereString word)
pattern T_IfExpression id conditions elses = OuterToken id (Inner_T_IfExpression conditions elses)
pattern T_Include id script = OuterToken id (Inner_T_Include script)
pattern T_IndexedElement id indices t = OuterToken id (Inner_T_IndexedElement indices t)
pattern T_IoDuplicate id op num = OuterToken id (Inner_T_IoDuplicate op num)
pattern T_IoFile id op file = OuterToken id (Inner_T_IoFile op file)
pattern T_NormalWord id list = OuterToken id (Inner_T_NormalWord list)
pattern T_OrIf id t u = OuterToken id (Inner_T_OrIf t u)
pattern T_Pipeline id l1 l2 = OuterToken id (Inner_T_Pipeline l1 l2)
pattern T_ProcSub id typ l = OuterToken id (Inner_T_ProcSub typ l)
pattern T_Redirecting id redirs cmd = OuterToken id (Inner_T_Redirecting redirs cmd)
pattern T_Script id shebang list = OuterToken id (Inner_T_Script shebang list)
pattern T_SelectIn id v w l = OuterToken id (Inner_T_SelectIn v w l)
pattern T_SimpleCommand id vars cmds = OuterToken id (Inner_T_SimpleCommand vars cmds)
pattern T_SourceCommand id includer t_include = OuterToken id (Inner_T_SourceCommand includer t_include)
pattern T_Subshell id l = OuterToken id (Inner_T_Subshell l)
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 #-}

instance Eq Token where
    OuterToken _ a == OuterToken _ b = a == b

analyze :: Monad m => (Token -> m ()) -> (Token -> m ()) -> (Token -> m Token) -> Token -> m Token
analyze f g i =
    round
  where
    round t@(OuterToken id it) = do
        f t
        newIt <- traverse round it
        g t
        i (OuterToken id newIt)

getId :: Token -> Id
getId (OuterToken id _) = id

blank :: Monad m => Token -> m ()
blank = const $ return ()
doAnalysis :: Monad m => (Token -> m ()) -> Token -> m Token
doAnalysis f = analyze f blank return
doStackAnalysis :: Monad m => (Token -> m ()) -> (Token -> m ()) -> Token -> m Token
doStackAnalysis startToken endToken = analyze startToken endToken return
doTransform :: (Token -> Token) -> Token -> Token
doTransform i = runIdentity . analyze blank blank (return . i)



================================================
FILE: src/ShellCheck/ASTLib.hs
================================================
{-
    Copyright 2012-2021 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 #-}
module ShellCheck.ASTLib where

import ShellCheck.AST
import ShellCheck.Prelude
import ShellCheck.Regex

import Control.Monad.Writer
import Control.Monad
import Data.Char
import Data.Functor
import Data.Functor.Identity
import Data.List
import Data.Maybe
import qualified Data.List.NonEmpty as NE
import qualified Data.Map as Map
import Numeric (showHex)

import Test.QuickCheck

arguments (T_SimpleCommand _ _ (cmd:args)) = args

-- Is this a type of loop?
isLoop t = case t of
        T_WhileExpression {} -> True
        T_UntilExpression {} -> True
        T_ForIn {} -> True
        T_ForArithmetic {} -> True
        T_SelectIn {}  -> True
        _ -> False

-- Will this split into multiple words when used as an argument?
willSplit x =
  case x of
    T_DollarBraced {} -> True
    T_DollarExpansion {} -> True
    T_Backticked {} -> True
    T_BraceExpansion {} -> True
    T_Glob {} -> True
    T_Extglob {} -> True
    T_DoubleQuoted _ l -> any willBecomeMultipleArgs l
    T_NormalWord _ l -> any willSplit l
    _ -> False

isGlob t = case t of
    T_Extglob {} -> True
    T_Glob {} -> True
    T_NormalWord _ l -> any isGlob l || hasSplitRange l
    _ -> False
  where
    -- foo[x${var}y] gets parsed as foo,[,x,$var,y],
    -- so check if there's such an interval
    hasSplitRange l =
        let afterBracket = dropWhile (not . isHalfOpenRange) l
        in any isClosingRange afterBracket

    isHalfOpenRange t =
        case t of
            T_Literal _ "[" -> True
            _ -> False

    isClosingRange t =
        case t of
            T_Literal _ str -> ']' `elem` str
            _ -> False


-- Is this shell word a constant?
isConstant token =
    case token of
        -- This ignores some cases like ~"foo":
        T_NormalWord _ (T_Literal _ ('~':_) : _)  -> False
        T_NormalWord _ l   -> all isConstant l
        T_DoubleQuoted _ l -> all isConstant l
        T_SingleQuoted _ _ -> True
        T_Literal _ _ -> True
        _ -> False

-- Is this an empty literal?
isEmpty token =
    case token of
        T_NormalWord _ l   -> all isEmpty l
        T_DoubleQuoted _ l -> all isEmpty l
        T_SingleQuoted _ "" -> True
        T_Literal _ "" -> True
        _ -> False

-- Quick&lazy oversimplification of commands, throwing away details
-- and returning a list like  ["find", ".", "-name", "${VAR}*" ].
oversimplify token =
    case token of
        (T_NormalWord _ l) -> [concat (concatMap oversimplify l)]
        (T_DoubleQuoted _ l) -> [concat (concatMap oversimplify l)]
        (T_SingleQuoted _ s) -> [s]
        (T_DollarBraced _ _ _) -> ["${VAR}"]
        (T_DollarArithmetic _ _) -> ["${VAR}"]
        (T_DollarExpansion _ _) -> ["${VAR}"]
        (T_Backticked _ _) -> ["${VAR}"]
        (T_Glob _ s) -> [s]
        (T_Pipeline _ _ [x]) -> oversimplify x
        (T_Literal _ x) -> [x]
        (T_ParamSubSpecialChar _ x) -> [x]
        (T_SimpleCommand _ vars words) -> concatMap oversimplify words
        (T_Redirecting _ _ foo) -> oversimplify foo
        (T_DollarSingleQuoted _ s) -> [s]
        (T_Annotation _ _ s) -> oversimplify s
        -- Workaround for let "foo = bar" parsing
        (TA_Sequence _ [TA_Expansion _ v]) -> concatMap oversimplify v
        _ -> []


-- Turn a SimpleCommand foo -avz --bar=baz into args "a", "v", "z", "bar",
-- each in a tuple of (token, stringFlag). Non-flag arguments are added with
-- stringFlag == "".
getFlagsUntil stopCondition (T_SimpleCommand _ _ (_:args)) =
    let tokenAndText = map (\x -> (x, concat $ oversimplify x)) args
        (flagArgs, rest) = break (stopCondition . snd) tokenAndText
    in
        concatMap flag flagArgs ++ map (\(t, _) -> (t, "")) rest
  where
    flag (x, '-':'-':arg) = [ (x, takeWhile (/= '=') arg) ]
    flag (x, '-':args) = map (\v -> (x, [v])) args
    flag (x, _) = [ (x, "") ]
getFlagsUntil _ _ = error $ pleaseReport "getFlags on non-command"

-- Get all flags in a GNU way, up until --
getAllFlags :: Token -> [(Token, String)]
getAllFlags = getFlagsUntil (== "--")
-- Get all flags in a BSD way, up until first non-flag argument or --
getLeadingFlags = getFlagsUntil (\x -> x == "--" || (not $ "-" `isPrefixOf` x))

-- Check if a command has a flag.
hasFlag cmd str = str `elem` (map snd $ getAllFlags cmd)

-- Is this token a word that starts with a dash?
isFlag token =
    case getWordParts token of
        T_Literal _ ('-':_) : _ -> True
        _ -> False

-- Is this token a flag where the - is unquoted?
isUnquotedFlag token =
    case getLeadingUnquotedString token of
        Just ('-':_) -> True
        _ -> False

-- getGnuOpts "erd:u:" will parse a list of arguments tokens like `read`
--     -re -d : -u 3 bar
-- into
--     Just [("r", (-re, -re)), ("e", (-re, -re)), ("d", (-d,:)), ("u", (-u,3)), ("", (bar,bar))]
--
-- Each string flag maps to a tuple of (flag, argument), where argument=flag if it
-- doesn't take a specific one.
--
-- Any unrecognized flag will result in Nothing. The exception is if arbitraryLongOpts
-- is set, in which case --anything will map to "anything".
getGnuOpts :: String -> [Token] -> Maybe [(String, (Token, Token))]
getGnuOpts str args = getOpts (True, False) str [] args

-- As above, except the first non-arg string will treat the rest as arguments
getBsdOpts :: String -> [Token] -> Maybe [(String, (Token, Token))]
getBsdOpts str args = getOpts (False, False) str [] args

-- Tests for this are in Commands.hs where it's more frequently used
getOpts ::
    -- Behavioral config: gnu style, allow arbitrary long options
    (Bool, Bool)
    -- A getopts style string
    -> String
    -- List of long options and whether they take arguments
    -> [(String, Bool)]
    -- List of arguments (excluding command)
    -> [Token]
    -- List of flags to tuple of (optionToken, valueToken)
    -> Maybe [(String, (Token, Token))]

getOpts (gnu, arbitraryLongOpts) string longopts args = process args
  where
    flagList (c:':':rest) = ([c], True) : flagList rest
    flagList (c:rest)     = ([c], False) : flagList rest
    flagList []           = longopts
    flagMap = Map.fromList $ ("", False) : flagList string

    process [] = return []
    process (token:rest) = do
        case getLiteralStringDef "\0" token of
            "--" -> return $ listToArgs rest
            '-':'-':word -> do
                let (name, arg) = span (/= '=') word
                needsArg <-
                    if arbitraryLongOpts
                    then return $ Map.findWithDefault False name flagMap
                    else Map.lookup name flagMap

                if needsArg && null arg
                  then
                    case rest of
                        (arg:rest2) -> do
                            more <- process rest2
                            return $ (name, (token, arg)) : more
                        _ -> fail "Missing arg"
                  else do
                    more <- process rest
                    -- Consider splitting up token to get arg
                    return $ (name, (token, token)) : more
            '-':opts -> shortToOpts opts token rest
            arg ->
                if gnu
                then do
                    more <- process rest
                    return $ ("", (token, token)):more
                else return $ listToArgs (token:rest)

    shortToOpts opts token args =
        case opts of
            c:rest -> do
                needsArg <- Map.lookup [c] flagMap
                case () of
                    _ | needsArg && null rest -> do
                        (next:restArgs) <- return args
                        more <- process restArgs
                        return $ ([c], (token, next)):more
                    _ | needsArg -> do
                        more <- process args
                        return $ ([c], (token, token)):more
                    _ -> do
                        more <- shortToOpts rest token args
                        return $ ([c], (token, token)):more
            [] -> process args

    listToArgs = map (\x -> ("", (x, x)))


-- Generic getOpts that doesn't rely on a format string, but may also be inaccurate.
-- This provides a best guess interpretation instead of failing when new options are added.
--
--    "--" is treated as end of arguments
--    "--anything[=foo]" is treated as a long option without argument
--    "-any" is treated as -a -n -y, with the next arg as an option to -y unless it starts with -
--    anything else is an argument
getGenericOpts :: [Token] -> [(String, (Token, Token))]
getGenericOpts = process
  where
    process (token:rest) =
        case getLiteralStringDef "\0" token of
            "--" -> map (\c -> ("", (c,c))) rest
            '-':'-':word -> (takeWhile (`notElem` "\0=") word, (token, token)) : process rest
            '-':optString ->
                let opts = takeWhile (/= '\0') optString
                in
                    case rest of
                        next:_ | "-" `isPrefixOf` getLiteralStringDef "\0" next  ->
                            map (\c -> ([c], (token, token))) opts ++ process rest
                        next:remainder ->
                            case reverse opts of
                                last:initial ->
                                    map (\c -> ([c], (token, token))) (reverse initial)
                                        ++ [([last], (token, next))]
                                        ++ process remainder
                                [] -> process remainder
                        [] -> map (\c -> ([c], (token, token))) opts
            _ -> ("", (token, token)) : process rest
    process [] = []


-- Is this an expansion of multiple items of an array?
isArrayExpansion (T_DollarBraced _ _ l) =
    let string = concat $ oversimplify l in
        "@" `isPrefixOf` string ||
            not ("#" `isPrefixOf` string) && "[@]" `isInfixOf` string
isArrayExpansion _ = False

-- Is it possible that this arg becomes multiple args?
mayBecomeMultipleArgs t = willBecomeMultipleArgs t || f False t
  where
    f quoted (T_DollarBraced _ _ l) =
        let string = concat $ oversimplify l in
            not quoted || "!" `isPrefixOf` string
    f quoted (T_DoubleQuoted _ parts) = any (f True) parts
    f quoted (T_NormalWord _ parts) = any (f quoted) parts
    f _ _ = False

-- Is it certain that this word will becomes multiple words?
willBecomeMultipleArgs t = willConcatInAssignment t || f t
  where
    f T_Extglob {} = True
    f T_Glob {} = True
    f T_BraceExpansion {} = True
    f (T_NormalWord _ parts) = any f parts
    f _ = False

-- This does token cause implicit concatenation in assignments?
willConcatInAssignment token =
    case token of
        t@T_DollarBraced {} -> isArrayExpansion t
        (T_DoubleQuoted _ parts) -> any willConcatInAssignment parts
        (T_NormalWord _ parts) -> any willConcatInAssignment parts
        _ -> False

-- Maybe get the literal string corresponding to this token
getLiteralString :: Token -> Maybe String
getLiteralString = getLiteralStringExt (const Nothing)

-- Definitely get a literal string, with a given default for all non-literals
getLiteralStringDef :: String -> Token -> String
getLiteralStringDef x = runIdentity . getLiteralStringExt (const $ return x)

-- Definitely get a literal string, skipping over all non-literals
onlyLiteralString :: Token -> String
onlyLiteralString = getLiteralStringDef ""

-- Maybe get a literal string, but only if it's an unquoted argument.
getUnquotedLiteral (T_NormalWord _ list) =
    concat <$> mapM str list
  where
    str (T_Literal _ s) = return s
    str _ = Nothing
getUnquotedLiteral _ = Nothing

isQuotes t =
    case t of
        T_DoubleQuoted {} -> True
        T_SingleQuoted {} -> True
        _ -> False

-- Get the last unquoted T_Literal in a word like "${var}foo"THIS
-- or nothing if the word does not end in an unquoted literal.
getTrailingUnquotedLiteral :: Token -> Maybe Token
getTrailingUnquotedLiteral t =
    case t of
        (T_NormalWord _ list@(_:_)) ->
            from (last list)
        _ -> Nothing
  where
    from t =
        case t of
            T_Literal {} -> return t
            _ -> Nothing

-- Get the leading, unquoted, literal string of a token (if any).
getLeadingUnquotedString :: Token -> Maybe String
getLeadingUnquotedString t =
    case t of
        T_NormalWord _ ((T_Literal _ s) : rest) -> return $ s ++ from rest
        _ -> Nothing
  where
    from ((T_Literal _ s):rest) = s ++ from rest
    from _ = ""

-- Maybe get the literal string of this token and any globs in it.
getGlobOrLiteralString = getLiteralStringExt f
  where
    f (T_Glob _ str) = return str
    f _ = Nothing


prop_getLiteralString1 = getLiteralString (T_DollarSingleQuoted (Id 0) "\\x01") == Just "\1"
prop_getLiteralString2 = getLiteralString (T_DollarSingleQuoted (Id 0) "\\xyz") == Just "\\xyz"
prop_getLiteralString3 = getLiteralString (T_DollarSingleQuoted (Id 0) "\\x1") == Just "\x1"
prop_getLiteralString4 = getLiteralString (T_DollarSingleQuoted (Id 0) "\\x1y") == Just "\x1y"
prop_getLiteralString5 = getLiteralString (T_DollarSingleQuoted (Id 0) "\\xy") == Just "\\xy"
prop_getLiteralString6 = getLiteralString (T_DollarSingleQuoted (Id 0) "\\x") == Just "\\x"
prop_getLiteralString7 = getLiteralString (T_DollarSingleQuoted (Id 0) "\\1x") == Just "\1x"
prop_getLiteralString8 = getLiteralString (T_DollarSingleQuoted (Id 0) "\\12x") == Just "\o12x"
prop_getLiteralString9 = getLiteralString (T_DollarSingleQuoted (Id 0) "\\123x") == Just "\o123x"
prop_getLiteralString10 = getLiteralString (T_DollarSingleQuoted (Id 0) "\\1234") == Just "\o123\&4"
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"

-- Maybe get the literal value of a token, using a custom function
-- to map unrecognized Tokens into strings.
getLiteralStringExt :: Monad m => (Token -> m String) -> Token -> m String
getLiteralStringExt more = g
  where
    allInList = fmap concat . mapM g
    g (T_DoubleQuoted _ l) = allInList l
    g (T_DollarDoubleQuoted _ l) = allInList l
    g (T_NormalWord _ l) = allInList l
    g (TA_Expansion _ l) = allInList l
    g (T_SingleQuoted _ s) = return s
    g (T_Literal _ s) = return s
    g (T_ParamSubSpecialChar _ s) = return s
    g (T_DollarSingleQuoted _ s) = return $ decodeEscapes s
    g x = more x

    -- Bash style $'..' decoding
    decodeEscapes ('\\':c:cs) =
        case c of
            'a' -> '\a' : rest
            'b' -> '\b' : rest
            'e' -> '\x1B' : rest
            'f' -> '\f' : rest
            'n' -> '\n' : rest
            'r' -> '\r' : rest
            't' -> '\t' : rest
            'v' -> '\v' : 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
      where
        rest = decodeEscapes cs
        parseOct = f 0
          where
            f n "" = n
            f n (c:rest) = f (n * 8 + digitToInt c) rest
        spanMax f n list =
            let (first, second) = span f list
                (prefix, suffix) = splitAt n first
            in
                (prefix, suffix ++ second)
    decodeEscapes (c:cs) = c : decodeEscapes cs
    decodeEscapes [] = []

-- Is this token a string literal?
isLiteral t = isJust $ getLiteralString t

-- Is this token a string literal number?
isLiteralNumber t = fromMaybe False $ do
    s <- getLiteralString t
    guard $ all isDigit s
    return True

-- Escape user data for messages.
-- Messages generally avoid repeating user data, but sometimes it's helpful.
e4m = escapeForMessage
escapeForMessage :: String -> String
escapeForMessage str = concatMap f str
  where
    f '\\' = "\\\\"
    f '\n' = "\\n"
    f '\r' = "\\r"
    f '\t' = "\\t"
    f '\x1B' = "\\e"
    f c =
        if shouldEscape c
        then
            if ord c < 256
            then "\\x" ++ (pad0 2 $ toHex c)
            else "\\U" ++ (pad0 4 $ toHex c)
        else [c]

    shouldEscape c =
        (not $ isPrint c)
        || (not (isAscii c) && not (isLetter c))

    pad0 :: Int -> String -> String
    pad0 n s =
        let l = length s in
            if l < n
            then (replicate (n-l) '0') ++ s
            else s
    toHex :: Char -> String
    toHex c = map toUpper $ showHex (ord c) ""

-- Turn a NormalWord like foo="bar $baz" into a series of constituent elements like [foo=,bar ,$baz]
getWordParts (T_NormalWord _ l)   = concatMap getWordParts l
getWordParts (T_DoubleQuoted _ l) = l
-- TA_Expansion is basically T_NormalWord for arithmetic expressions
getWordParts (TA_Expansion _ l)   = concatMap getWordParts l
getWordParts other                = [other]

-- Return a list of NormalWords that would result from brace expansion
braceExpand (T_NormalWord id list) = take 1000 $ do
    items <- mapM part list
    return $ T_NormalWord id items
  where
    part (T_BraceExpansion id items) = do
        item <- items
        braceExpand item
    part x = return x

-- Maybe get a SimpleCommand from immediate wrappers like T_Redirections
getCommand t =
    case t of
        T_Redirecting _ _ w -> getCommand w
        T_SimpleCommand _ _ (w:_) -> return t
        T_Annotation _ _ t -> getCommand t
        _ -> Nothing

-- Maybe get the command name string of a token representing a command
getCommandName :: Token -> Maybe String
getCommandName = fst . getCommandNameAndToken False

-- Maybe get the name+arguments of a command.
getCommandArgv t = do
    (T_SimpleCommand _ _ args@(_:_)) <- getCommand t
    return args

-- Get the command name token from a command, i.e.
-- the token representing 'ls' in 'ls -la 2> foo'.
-- If it can't be determined, return the original token.
getCommandTokenOrThis = snd . getCommandNameAndToken False

-- Given a command, get the string and token that represents the command name.
-- If direct, return the actual command (e.g. exec in 'exec ls')
-- If not, return the logical command (e.g. 'ls' in 'exec ls')

getCommandNameAndToken :: Bool -> Token -> (Maybe String, Token)
getCommandNameAndToken direct t = fromMaybe (Nothing, t) $ do
    cmd@(T_SimpleCommand _ _ (w:rest)) <- getCommand t
    s <- getLiteralString w
    return $ fromMaybe (Just s, w) $ do
        guard $ not direct
        actual <- getEffectiveCommandToken s cmd rest
        return (getLiteralString actual, actual)
  where
    getEffectiveCommandToken str cmd args =
        let
            firstArg = do
                arg <- listToMaybe args
                guard . not $ isFlag arg
                return arg
        in
            case str of
                "busybox" -> firstArg
                "builtin" -> firstArg
                "command" -> firstArg
                "run" -> firstArg -- Used by bats
                "exec" -> do
                    opts <- getBsdOpts "cla:" args
                    (_, (t, _)) <- find (null . fst) opts
                    return t
                _ -> fail ""

-- If a command substitution is a single command, get its name.
--  $(date +%s) = Just "date"
getCommandNameFromExpansion :: Token -> Maybe String
getCommandNameFromExpansion t =
    case t of
        T_DollarExpansion _ [c] -> extract c
        T_Backticked _ [c] -> extract c
        T_DollarBraceCommandExpansion _ _ [c] -> extract c
        _ -> Nothing
  where
    extract (T_Pipeline _ _ [cmd]) = getCommandName cmd
    extract _ = Nothing

-- Get the basename of a token representing a command
getCommandBasename = fmap basename . getCommandName

basename = reverse . takeWhile (/= '/') . reverse

isAssignment t =
    case t of
        T_Redirecting _ _ w -> isAssignment w
        T_SimpleCommand _ (w:_) [] -> True
        T_Assignment {} -> True
        T_Annotation _ _ w -> isAssignment w
        _ -> False

isOnlyRedirection t =
    case t of
        T_Pipeline _ _ [x] -> isOnlyRedirection x
        T_Annotation _ _ w -> isOnlyRedirection w
        T_Redirecting _ (_:_) c -> isOnlyRedirection c
        T_SimpleCommand _ [] [] -> True
        _ -> False

isFunction t = case t of T_Function {} -> True; _ -> False

-- Bats tests are functions for the purpose of 'local' and such
isFunctionLike t =
    case t of
        T_Function {} -> True
        T_BatsTest {} -> True
        _ -> False


isBraceExpansion t = case t of T_BraceExpansion {} -> True; _ -> False

-- Get the lists of commands from tokens that contain them, such as
-- the conditions and bodies of while loops or branches of if statements.
getCommandSequences :: Token -> [[Token]]
getCommandSequences t =
    case t of
        T_Script _ _ cmds -> [cmds]
        T_BraceGroup _ cmds -> [cmds]
        T_Subshell _ cmds -> [cmds]
        T_WhileExpression _ cond cmds -> [cond, cmds]
        T_UntilExpression _ cond cmds -> [cond, cmds]
        T_ForIn _ _ _ cmds -> [cmds]
        T_ForArithmetic _ _ _ _ cmds -> [cmds]
        T_IfExpression _ thens elses -> (concatMap (\(a,b) -> [a,b]) thens) ++ [elses]
        T_Annotation _ _ t -> getCommandSequences t

        T_DollarExpansion _ cmds -> [cmds]
        T_DollarBraceCommandExpansion _ _ cmds -> [cmds]
        T_Backticked _ cmds -> [cmds]
        _ -> []

-- Get a list of names of associative arrays
getAssociativeArrays t =
    nub . execWriter $ doAnalysis f t
  where
    f :: Token -> Writer [String] ()
    f t@T_SimpleCommand {} = sequence_ $ do
        name <- getCommandName t
        let assocNames = ["declare","local","typeset"]
        guard $ name `elem` assocNames
        let flags = getAllFlags t
        guard $ "A" `elem` map snd flags
        let args = [arg | (arg, "") <- flags]
        let names = mapMaybe (getLiteralStringExt nameAssignments) args
        return $ tell names
    f _ = return ()

    nameAssignments t =
        case t of
            T_Assignment _ _ name _ _ -> return name
            _ -> Nothing

-- A Pseudoglob is a wildcard pattern used for checking if a match can succeed.
-- For example, [[ $(cmd).jpg == [a-z] ]] will give the patterns *.jpg and ?, which
-- can be proven never to match.
data PseudoGlob = PGAny | PGMany | PGChar Char
    deriving (Eq, Show)

-- Turn a word into a PG pattern, replacing all unknown/runtime values with
-- PGMany.
wordToPseudoGlob :: Token -> [PseudoGlob]
wordToPseudoGlob = fromMaybe [PGMany] . wordToPseudoGlob' False

-- Turn a word into a PG pattern, but only if we can preserve
-- exact semantics.
wordToExactPseudoGlob :: Token -> Maybe [PseudoGlob]
wordToExactPseudoGlob = wordToPseudoGlob' True

wordToPseudoGlob' :: Bool -> Token -> Maybe [PseudoGlob]
wordToPseudoGlob' exact word =
    simplifyPseudoGlob <$> toGlob word
  where
    toGlob :: Token -> Maybe [PseudoGlob]
    toGlob word =
        case word of
            T_NormalWord _ (T_Literal _ ('~':str):rest) -> do
                guard $ not exact
                let this = (PGMany : (map PGChar $ dropWhile (/= '/') str))
                tail <- concat <$> (mapM f $ concatMap getWordParts rest)
                return $ this ++ tail
            _ -> concat <$> (mapM f $ getWordParts word)

    f x = case x of
        T_Literal _ s      -> return $ map PGChar s
        T_SingleQuoted _ s -> return $ map PGChar s
        T_Glob _ "?"       -> return [PGAny]
        T_Glob _ "*"       -> return [PGMany]
        T_Glob _ ('[':_) | not exact -> return [PGAny]
        _ -> if exact then fail "" else return [PGMany]


-- Reorder a PseudoGlob for more efficient matching, e.g.
-- f?*?**g -> f??*g
simplifyPseudoGlob :: [PseudoGlob] -> [PseudoGlob]
simplifyPseudoGlob = f
  where
    f [] = []
    f (x@(PGChar _) : rest ) = x : f rest
    f list =
        let (anys, rest) = span (\x -> x == PGMany || x == PGAny) list in
            order anys ++ f rest

    order s = let (any, many) = partition (== PGAny) s in
        any ++ take 1 many

-- Check whether the two patterns can ever overlap.
pseudoGlobsCanOverlap :: [PseudoGlob] -> [PseudoGlob] -> Bool
pseudoGlobsCanOverlap = matchable
  where
    matchable x@(xf:xs) y@(yf:ys) =
        case (xf, yf) of
            (PGMany, _) -> matchable x ys || matchable xs y
            (_, PGMany) -> matchable x ys || matchable xs y
            (PGAny, _) -> matchable xs ys
            (_, PGAny) -> matchable xs ys
            (_, _) -> xf == yf && matchable xs ys

    matchable [] [] = True
    matchable (PGMany : rest) [] = matchable rest []
    matchable (_:_) [] = False
    matchable [] r = matchable r []

-- Check whether the first pattern always overlaps the second.
pseudoGlobIsSuperSetof :: [PseudoGlob] -> [PseudoGlob] -> Bool
pseudoGlobIsSuperSetof = matchable
  where
    matchable x@(xf:xs) y@(yf:ys) =
        case (xf, yf) of
            (PGMany, PGMany) -> matchable x ys
            (PGMany, _) -> matchable x ys || matchable xs y
            (_, PGMany) -> False
            (PGAny, _) -> matchable xs ys
            (_, PGAny) -> False
            (_, _) -> xf == yf && matchable xs ys

    matchable [] [] = True
    matchable (PGMany : rest) [] = matchable rest []
    matchable _ _ = False

wordsCanBeEqual x y = pseudoGlobsCanOverlap (wordToPseudoGlob x) (wordToPseudoGlob y)

-- Is this an expansion that can be quoted,
-- e.g. $(foo) `foo` $foo (but not {foo,})?
isQuoteableExpansion t = case t of
    T_DollarBraced {} -> True
    _ -> isCommandSubstitution t

isCommandSubstitution t = case t of
    T_DollarExpansion {} -> True
    T_DollarBraceCommandExpansion {} -> True
    T_Backticked {} -> True
    _ -> False

-- Is this an expansion that results in a simple string?
isStringExpansion t = isCommandSubstitution t || case t of
    T_DollarArithmetic {} -> True
    T_DollarBraced {} -> not (isArrayExpansion t)
    _ -> False

-- Is this a T_Annotation that ignores a specific code?
isAnnotationIgnoringCode code t =
    case t of
        T_Annotation _ anns _ -> any hasNum anns
        _ -> False
  where
    hasNum (DisableComment from to) = code >= from && code < to
    hasNum _                   = False

prop_executableFromShebang1 = executa
Download .txt
gitextract_k_64siyw/

├── .dockerignore
├── .ghci
├── .github/
│   ├── ISSUE_TEMPLATE/
│   │   ├── bug_report.md
│   │   └── feature_request.md
│   ├── dependabot.yml
│   └── workflows/
│       └── build.yml
├── .github_deploy
├── .gitignore
├── .multi_arch_docker
├── .prepare_deploy
├── .vscode/
│   └── extensions.json
├── CHANGELOG.md
├── Dockerfile.multi-arch
├── LICENSE
├── README.md
├── ShellCheck.cabal
├── builders/
│   ├── README.md
│   ├── build_builder
│   ├── darwin.aarch64/
│   │   ├── Dockerfile
│   │   ├── build
│   │   └── tag
│   ├── darwin.x86_64/
│   │   ├── Dockerfile
│   │   ├── build
│   │   └── tag
│   ├── linux.aarch64/
│   │   ├── Dockerfile
│   │   ├── build
│   │   └── tag
│   ├── linux.armv6hf/
│   │   ├── Dockerfile
│   │   ├── build
│   │   ├── scutil
│   │   └── tag
│   ├── linux.riscv64/
│   │   ├── Dockerfile
│   │   ├── build
│   │   └── tag
│   ├── linux.x86_64/
│   │   ├── Dockerfile
│   │   ├── build
│   │   └── tag
│   ├── run_builder
│   └── windows.x86_64/
│       ├── Dockerfile
│       ├── build
│       └── tag
├── manpage
├── nextnumber
├── quickrun
├── quicktest
├── setgitversion
├── shellcheck.1.md
├── shellcheck.hs
├── snap/
│   └── snapcraft.yaml
├── src/
│   └── ShellCheck/
│       ├── AST.hs
│       ├── ASTLib.hs
│       ├── Analytics.hs
│       ├── Analyzer.hs
│       ├── AnalyzerLib.hs
│       ├── CFG.hs
│       ├── CFGAnalysis.hs
│       ├── Checker.hs
│       ├── Checks/
│       │   ├── Commands.hs
│       │   ├── ControlFlow.hs
│       │   ├── Custom.hs
│       │   └── ShellSupport.hs
│       ├── Data.hs
│       ├── Debug.hs
│       ├── Fixer.hs
│       ├── Formatter/
│       │   ├── CheckStyle.hs
│       │   ├── Diff.hs
│       │   ├── Format.hs
│       │   ├── GCC.hs
│       │   ├── JSON.hs
│       │   ├── JSON1.hs
│       │   ├── Quiet.hs
│       │   └── TTY.hs
│       ├── Interface.hs
│       ├── Parser.hs
│       ├── Prelude.hs
│       └── Regex.hs
├── stack.yaml
├── striptests
└── test/
    ├── buildtest
    ├── check_release
    ├── distrotest
    ├── shellcheck.hs
    └── stacktest
Condensed preview — 83 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (1,008K chars).
[
  {
    "path": ".dockerignore",
    "chars": 59,
    "preview": "*\n!LICENSE\n!Setup.hs\n!ShellCheck.cabal\n!shellcheck.hs\n!src\n"
  },
  {
    "path": ".ghci",
    "chars": 32,
    "preview": ":set -idist/build/autogen -isrc\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.md",
    "chars": 624,
    "preview": "---\nname: Bug report\nabout: Create a new bug report\ntitle: ''\nlabels: ''\nassignees: ''\n\n---\n\n#### For bugs with existing"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature_request.md",
    "chars": 549,
    "preview": "---\nname: Feature request\nabout: Suggest an idea for this project\ntitle: ''\nlabels: ''\nassignees: ''\n\n---\n\n#### For new "
  },
  {
    "path": ".github/dependabot.yml",
    "chars": 118,
    "preview": "version: 2\n\nupdates:\n  - package-ecosystem: \"github-actions\"\n    directory: \"/\"\n    schedule:\n      interval: \"daily\"\n"
  },
  {
    "path": ".github/workflows/build.yml",
    "chars": 4949,
    "preview": "name: Build ShellCheck\n\n# Run this workflow every time a new commit pushed to your repository\non: [push, pull_request]\n\n"
  },
  {
    "path": ".github_deploy",
    "chars": 558,
    "preview": "#!/bin/bash\nset -x\nshopt -s extglob\n\nexport EDITOR=\"touch\"\n\n# Sanity check\ngh --version || exit 1\nhub release show lates"
  },
  {
    "path": ".gitignore",
    "chars": 318,
    "preview": "# Created by https://www.gitignore.io\n\n### Haskell ###\ndist\ncabal-dev\n*.o\n*.hi\n*.chi\n*.chs.h\n.virtualenv\n.hsenv\n.cabal-s"
  },
  {
    "path": ".multi_arch_docker",
    "chars": 3029,
    "preview": "#!/bin/bash\n# This script builds and deploys multi-architecture docker images from the\n# binaries previously built and d"
  },
  {
    "path": ".prepare_deploy",
    "chars": 1075,
    "preview": "#!/bin/bash\n# This script packages up compiled binaries\nset -ex\nshopt -s nullglob extglob\n\nls -l\n\ncp ../LICENSE LICENSE."
  },
  {
    "path": ".vscode/extensions.json",
    "chars": 63,
    "preview": "{\n    \"recommendations\": [\n        \"haskell.haskell\",\n    ],\n}\n"
  },
  {
    "path": "CHANGELOG.md",
    "chars": 23440,
    "preview": "## Git\n### Added\n\n### Changed\n\n### Fixed\n\n### Removed\n- SC3003: removed since ANSI C string is specified in POSIX.1-2024"
  },
  {
    "path": "Dockerfile.multi-arch",
    "chars": 786,
    "preview": "# Alpine image\nFROM alpine:latest AS alpine\nLABEL maintainer=\"Vidar Holen <vidar@vidarholen.net>\"\nARG tag\n\n# Put the rig"
  },
  {
    "path": "LICENSE",
    "chars": 35149,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
  },
  {
    "path": "README.md",
    "chars": 21156,
    "preview": "[![Build Status](https://github.com/koalaman/shellcheck/actions/workflows/build.yml/badge.svg)](https://github.com/koala"
  },
  {
    "path": "ShellCheck.cabal",
    "chars": 4050,
    "preview": "Name:             ShellCheck\nVersion:          0.11.0\nSynopsis:         Shell script analysis tool\nLicense:          GPL"
  },
  {
    "path": "builders/README.md",
    "chars": 766,
    "preview": "This directory contains Dockerfiles for all builds.\n\nA build image will:\n\n* Run on Linux x86\\_64 with vanilla Docker (no"
  },
  {
    "path": "builders/build_builder",
    "chars": 204,
    "preview": "#!/bin/sh\nif [ $# -eq 0 ]\nthen\n  echo >&2 \"No build image directories specified\"\n  echo >&2 \"Example: $0 build/*/\"\n  exi"
  },
  {
    "path": "builders/darwin.aarch64/Dockerfile",
    "chars": 1678,
    "preview": "FROM ghcr.io/shepherdjerred/macos-cross-compiler@sha256:7d40c5e179d5d15453cf2a6b1bba3392bb1448b8257ee6b86021fc905c59dad6"
  },
  {
    "path": "builders/darwin.aarch64/build",
    "chars": 536,
    "preview": "#!/bin/sh\nset -xe\n{\n  tar xzv --strip-components=1\n  chmod +x striptests && ./striptests\n  mkdir \"$TARGETNAME\"\n  ( IFS='"
  },
  {
    "path": "builders/darwin.aarch64/tag",
    "chars": 34,
    "preview": "koalaman/scbuilder-darwin-aarch64\n"
  },
  {
    "path": "builders/darwin.x86_64/Dockerfile",
    "chars": 1304,
    "preview": "FROM liushuyu/osxcross@sha256:fa32af4677e2860a1c5950bc8c360f309e2a87e2ddfed27b642fddf7a6093b76\n\nENV TARGET=x86_64-apple-"
  },
  {
    "path": "builders/darwin.x86_64/build",
    "chars": 332,
    "preview": "#!/bin/sh\nset -xe\n{\n  tar xzv --strip-components=1\n  chmod +x striptests && ./striptests\n  mkdir \"$TARGETNAME\"\n  ( IFS='"
  },
  {
    "path": "builders/darwin.x86_64/tag",
    "chars": 33,
    "preview": "koalaman/scbuilder-darwin-x86_64\n"
  },
  {
    "path": "builders/linux.aarch64/Dockerfile",
    "chars": 1767,
    "preview": "FROM ubuntu:25.04\n\nENV TARGET=aarch64-linux-gnu\nENV TARGETNAME=linux.aarch64\n\n# Build dependencies\nUSER root\nENV DEBIAN_"
  },
  {
    "path": "builders/linux.aarch64/build",
    "chars": 423,
    "preview": "#!/bin/sh\nset -xe\n{\n  tar xzv --strip-components=1\n  chmod +x striptests && ./striptests\n  mkdir \"$TARGETNAME\"\n  ( IFS='"
  },
  {
    "path": "builders/linux.aarch64/tag",
    "chars": 33,
    "preview": "koalaman/scbuilder-linux-aarch64\n"
  },
  {
    "path": "builders/linux.armv6hf/Dockerfile",
    "chars": 1673,
    "preview": "# This Docker file uses a custom QEmu fork with patches to follow execve\n# to build all of ShellCheck emulated.\n\nFROM ub"
  },
  {
    "path": "builders/linux.armv6hf/build",
    "chars": 525,
    "preview": "#!/bin/sh\nset -xe\nmkdir /scratch && cd /scratch\n{\n  tar xzv --strip-components=1\n  cp /etc/cabal.project.freeze .\n  chmo"
  },
  {
    "path": "builders/linux.armv6hf/scutil",
    "chars": 1190,
    "preview": "#!/bin/dash\n# Various ShellCheck build utility functions\n\n# Generally set a ulimit to avoid QEmu using too much memory\nu"
  },
  {
    "path": "builders/linux.armv6hf/tag",
    "chars": 33,
    "preview": "koalaman/scbuilder-linux-armv6hf\n"
  },
  {
    "path": "builders/linux.riscv64/Dockerfile",
    "chars": 1767,
    "preview": "FROM ubuntu:25.04\n\nENV TARGETNAME=linux.riscv64\nENV TARGET=riscv64-linux-gnu\n\n# Build dependencies\nUSER root\nENV DEBIAN_"
  },
  {
    "path": "builders/linux.riscv64/build",
    "chars": 423,
    "preview": "#!/bin/sh\nset -xe\n{\n  tar xzv --strip-components=1\n  chmod +x striptests && ./striptests\n  mkdir \"$TARGETNAME\"\n  ( IFS='"
  },
  {
    "path": "builders/linux.riscv64/tag",
    "chars": 33,
    "preview": "koalaman/scbuilder-linux-riscv64\n"
  },
  {
    "path": "builders/linux.x86_64/Dockerfile",
    "chars": 993,
    "preview": "FROM alpine:3.22\n# alpine:3.16 (GHC 9.0.1):  5.8 megabytes (certs expired)\n# alpine:3.17 (GHC 9.0.2): 15.0 megabytes (ce"
  },
  {
    "path": "builders/linux.x86_64/build",
    "chars": 400,
    "preview": "#!/bin/sh\nset -xe\n{\n  tar xzv --strip-components=1\n  chmod +x striptests && ./striptests\n  mkdir \"$TARGETNAME\"\n  cabal u"
  },
  {
    "path": "builders/linux.x86_64/tag",
    "chars": 32,
    "preview": "koalaman/scbuilder-linux-x86_64\n"
  },
  {
    "path": "builders/run_builder",
    "chars": 477,
    "preview": "#!/bin/bash\nif [ $# -lt 2 ]\nthen\n  echo >&2 \"This script builds a source archive (as produced by cabal sdist)\"\n  echo >&"
  },
  {
    "path": "builders/windows.x86_64/Dockerfile",
    "chars": 1416,
    "preview": "FROM ubuntu:25.04\n\nENV TARGETNAME=windows.x86_64\n\n# We don't need wine32, even though it complains\nUSER root\nENV DEBIAN_"
  },
  {
    "path": "builders/windows.x86_64/build",
    "chars": 463,
    "preview": "#!/bin/sh\ncabal() {\n  wine /haskell/bin/cabal.exe  \"$@\"\n}\n\nset -xe\n{\n  tar xzv --strip-components=1\n  chmod +x striptest"
  },
  {
    "path": "builders/windows.x86_64/tag",
    "chars": 34,
    "preview": "koalaman/scbuilder-windows-x86_64\n"
  },
  {
    "path": "manpage",
    "chars": 189,
    "preview": "#!/bin/sh\necho >&2 \"Generating man page using pandoc\"\npandoc -s -f markdown-smart -t man shellcheck.1.md -o shellcheck.1"
  },
  {
    "path": "nextnumber",
    "chars": 324,
    "preview": "#!/usr/bin/env bash\n# TODO: Find a less trashy way to get the next available error code\nif ! shopt -s globstar\nthen\n  ec"
  },
  {
    "path": "quickrun",
    "chars": 378,
    "preview": "#!/usr/bin/env bash\n# quickrun runs ShellCheck in an interpreted mode.\n# This allows testing changes without recompiling"
  },
  {
    "path": "quicktest",
    "chars": 616,
    "preview": "#!/usr/bin/env bash\n# quicktest runs the ShellCheck unit tests in an interpreted mode.\n# This allows running tests witho"
  },
  {
    "path": "setgitversion",
    "chars": 404,
    "preview": "#!/bin/sh -xe\n# This script hardcodes the `git describe` version as ShellCheck's version number.\n# This is done to allow"
  },
  {
    "path": "shellcheck.1.md",
    "chars": 13800,
    "preview": "% SHELLCHECK(1) Shell script analysis tool\n\n# NAME\n\nshellcheck - Shell script analysis tool\n\n# SYNOPSIS\n\n**shellcheck** "
  },
  {
    "path": "shellcheck.hs",
    "chars": 21925,
    "preview": "{-\n    Copyright 2012-2019 Vidar Holen\n\n    This file is part of ShellCheck.\n    https://www.shellcheck.net\n\n    ShellCh"
  },
  {
    "path": "snap/snapcraft.yaml",
    "chars": 1611,
    "preview": "name: shellcheck\nsummary: A shell script static analysis tool\ndescription: |\n  ShellCheck is a GPLv3 tool that gives war"
  },
  {
    "path": "src/ShellCheck/AST.hs",
    "chars": 14112,
    "preview": "{-\n    Copyright 2012-2019 Vidar Holen\n\n    This file is part of ShellCheck.\n    https://www.shellcheck.net\n\n    ShellCh"
  },
  {
    "path": "src/ShellCheck/ASTLib.hs",
    "chars": 34574,
    "preview": "{-\n    Copyright 2012-2021 Vidar Holen\n\n    This file is part of ShellCheck.\n    https://www.shellcheck.net\n\n    ShellCh"
  },
  {
    "path": "src/ShellCheck/Analytics.hs",
    "chars": 268222,
    "preview": "{-\n    Copyright 2012-2024 Vidar Holen\n\n    This file is part of ShellCheck.\n    https://www.shellcheck.net\n\n    ShellCh"
  },
  {
    "path": "src/ShellCheck/Analyzer.hs",
    "chars": 1891,
    "preview": "{-\n    Copyright 2012-2022 Vidar Holen\n\n    This file is part of ShellCheck.\n    https://www.shellcheck.net\n\n    ShellCh"
  },
  {
    "path": "src/ShellCheck/AnalyzerLib.hs",
    "chars": 35870,
    "preview": "{-\n    Copyright 2012-2022 Vidar Holen\n\n    This file is part of ShellCheck.\n    https://www.shellcheck.net\n\n    ShellCh"
  },
  {
    "path": "src/ShellCheck/CFG.hs",
    "chars": 49282,
    "preview": "{-\n    Copyright 2022 Vidar Holen\n\n    This file is part of ShellCheck.\n    https://www.shellcheck.net\n\n    ShellCheck i"
  },
  {
    "path": "src/ShellCheck/CFGAnalysis.hs",
    "chars": 54915,
    "preview": "{-\n    Copyright 2022 Vidar Holen\n\n    This file is part of ShellCheck.\n    https://www.shellcheck.net\n\n    ShellCheck i"
  },
  {
    "path": "src/ShellCheck/Checker.hs",
    "chars": 19919,
    "preview": "{-\n    Copyright 2012-2022 Vidar Holen\n\n    This file is part of ShellCheck.\n    https://www.shellcheck.net\n\n    ShellCh"
  },
  {
    "path": "src/ShellCheck/Checks/Commands.hs",
    "chars": 71323,
    "preview": "{-\n    Copyright 2012-2022 Vidar Holen\n\n    This file is part of ShellCheck.\n    https://www.shellcheck.net\n\n    ShellCh"
  },
  {
    "path": "src/ShellCheck/Checks/ControlFlow.hs",
    "chars": 3359,
    "preview": "{-\n    Copyright 2022 Vidar Holen\n\n    This file is part of ShellCheck.\n    https://www.shellcheck.net\n\n    ShellCheck i"
  },
  {
    "path": "src/ShellCheck/Checks/Custom.hs",
    "chars": 533,
    "preview": "{-\n    This empty file is provided for ease of patching in site specific checks.\n    However, there are no guarantees re"
  },
  {
    "path": "src/ShellCheck/Checks/ShellSupport.hs",
    "chars": 34547,
    "preview": "{-\n    Copyright 2012-2020 Vidar Holen\n\n    This file is part of ShellCheck.\n    https://www.shellcheck.net\n\n    ShellCh"
  },
  {
    "path": "src/ShellCheck/Data.hs",
    "chars": 6919,
    "preview": "module ShellCheck.Data where\n\nimport ShellCheck.Interface\nimport Data.Version (showVersion)\n\n\n{-\nIf you are here because"
  },
  {
    "path": "src/ShellCheck/Debug.hs",
    "chars": 9074,
    "preview": "{-\n\nThis file contains useful functions for debugging and developing ShellCheck.\n\nTo invoke them interactively, run:\n\n  "
  },
  {
    "path": "src/ShellCheck/Fixer.hs",
    "chars": 13368,
    "preview": "{-\n    Copyright 2018-2019 Vidar Holen, Ng Zhi An\n\n    This file is part of ShellCheck.\n    https://www.shellcheck.net\n\n"
  },
  {
    "path": "src/ShellCheck/Formatter/CheckStyle.hs",
    "chars": 2826,
    "preview": "{-\n    Copyright 2012-2019 Vidar Holen\n\n    This file is part of ShellCheck.\n    https://www.shellcheck.net\n\n    ShellCh"
  },
  {
    "path": "src/ShellCheck/Formatter/Diff.hs",
    "chars": 9129,
    "preview": "{-\n    Copyright 2019 Vidar 'koala_man' Holen\n\n    This file is part of ShellCheck.\n    https://www.shellcheck.net\n\n    "
  },
  {
    "path": "src/ShellCheck/Formatter/Format.hs",
    "chars": 2561,
    "preview": "{-\n    Copyright 2012-2019 Vidar Holen\n\n    This file is part of ShellCheck.\n    https://www.shellcheck.net\n\n    ShellCh"
  },
  {
    "path": "src/ShellCheck/Formatter/GCC.hs",
    "chars": 2017,
    "preview": "{-\n    Copyright 2012-2019 Vidar Holen\n\n    This file is part of ShellCheck.\n    https://www.shellcheck.net\n\n    ShellCh"
  },
  {
    "path": "src/ShellCheck/Formatter/JSON.hs",
    "chars": 3307,
    "preview": "{-# LANGUAGE OverloadedStrings #-}\n{-\n    Copyright 2012-2019 Vidar Holen\n\n    This file is part of ShellCheck.\n    http"
  },
  {
    "path": "src/ShellCheck/Formatter/JSON1.hs",
    "chars": 3878,
    "preview": "{-# LANGUAGE OverloadedStrings #-}\n{-\n    Copyright 2012-2019 Vidar Holen\n\n    This file is part of ShellCheck.\n    http"
  },
  {
    "path": "src/ShellCheck/Formatter/Quiet.hs",
    "chars": 1198,
    "preview": "{-\n    Copyright 2019 Austin Voecks\n\n    This file is part of ShellCheck.\n    https://www.shellcheck.net\n\n    ShellCheck"
  },
  {
    "path": "src/ShellCheck/Formatter/TTY.hs",
    "chars": 7196,
    "preview": "{-\n    Copyright 2012-2019 Vidar Holen\n\n    This file is part of ShellCheck.\n    https://www.shellcheck.net\n\n    ShellCh"
  },
  {
    "path": "src/ShellCheck/Interface.hs",
    "chars": 9691,
    "preview": "{-\n    Copyright 2012-2024 Vidar Holen\n\n    This file is part of ShellCheck.\n    https://www.shellcheck.net\n\n    ShellCh"
  },
  {
    "path": "src/ShellCheck/Parser.hs",
    "chars": 135442,
    "preview": "{-\n    Copyright 2012-2022 Vidar Holen\n\n    This file is part of ShellCheck.\n    https://www.shellcheck.net\n\n    ShellCh"
  },
  {
    "path": "src/ShellCheck/Prelude.hs",
    "chars": 1540,
    "preview": "{-\n    Copyright 2022 Vidar Holen\n\n    This file is part of ShellCheck.\n    https://www.shellcheck.net\n\n    ShellCheck i"
  },
  {
    "path": "src/ShellCheck/Regex.hs",
    "chars": 2651,
    "preview": "{-\n    Copyright 2012-2019 Vidar Holen\n\n    This file is part of ShellCheck.\n    https://www.shellcheck.net\n\n    ShellCh"
  },
  {
    "path": "stack.yaml",
    "chars": 1133,
    "preview": "# This file was automatically generated by stack init\n# For more information, see: https://docs.haskellstack.org/en/stab"
  },
  {
    "path": "striptests",
    "chars": 1430,
    "preview": "#!/usr/bin/env bash\n# This file strips all unit tests from ShellCheck, removing\n# the dependency on QuickCheck and Templ"
  },
  {
    "path": "test/buildtest",
    "chars": 1390,
    "preview": "#!/bin/bash\n# This script configures, builds and runs tests.\n# It's meant for automatic cross-distro testing.\n\ndie() { e"
  },
  {
    "path": "test/check_release",
    "chars": 2713,
    "preview": "#!/usr/bin/env bash\n# shellcheck disable=SC2257\n\nfailed=0\nfail() {\n  echo \"$(tput setaf 1)$*$(tput sgr0)\"\n  failed=1\n}\n\n"
  },
  {
    "path": "test/distrotest",
    "chars": 2750,
    "preview": "#!/bin/bash\n# This script runs 'buildtest' on each of several distros\n# via Docker.\nset -o pipefail\n\nexec 3>&1 4>&2\ndie("
  },
  {
    "path": "test/shellcheck.hs",
    "chars": 1737,
    "preview": "module Main where\n\nimport Control.Monad\nimport System.Exit\nimport qualified ShellCheck.Analytics\nimport qualified ShellC"
  },
  {
    "path": "test/stacktest",
    "chars": 865,
    "preview": "#!/bin/bash\n# This script builds ShellCheck through `stack` using\n# various resolvers. It's run via distrotest.\n\nresolve"
  }
]

About this extraction

This page contains the full source code of the koalaman/shellcheck GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 83 files (940.6 KB), approximately 255.3k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!