1167 Commits

Author SHA1 Message Date
Vidar Holen
21462b11b3 Merge branch 'doctest-new-build' of https://github.com/phadej/shellcheck into phadej-doctest-new-build 2018-12-16 18:33:21 -08:00
Vidar Holen
88aef838f1 SC1068 (var = x) now alternatively suggests quoting (fixes #1412) 2018-12-16 15:45:52 -08:00
Vidar Holen
3d61b73e91 Be more specific about why you should read the wiki page 2018-12-16 15:14:29 -08:00
Vidar Holen
138080bdc7 Fix infinite loop on annotations for SC2188 (fixes #1413) 2018-12-16 14:42:19 -08:00
Vidar Holen
5b3f17c29d Allow tests to access token positions for fixes 2018-12-16 13:17:59 -08:00
Vidar Holen
b47e083ee3 Fix 'does not support multiple targets at once' error 2018-12-16 10:15:32 -08:00
Vidar Holen
3cba76dc7d Update CHANGELOG with new release and autofix merge 2018-12-09 15:01:08 -08:00
Vidar Holen
eb588f62f6 Enable autofix support. It's still preliminary. 2018-12-09 15:01:08 -08:00
Vidar Holen
bcd13614eb Improve Fix memory usage 2018-12-09 15:01:08 -08:00
Vidar Holen
a8376a09a9 Minor renaming and output fixes 2018-12-09 15:01:08 -08:00
Ng Zhi An
5ed89d2241 Change definition of Replacement, add ToJSON instance for it 2018-12-09 15:01:08 -08:00
Ng Zhi An
4a87d2a3de Expose token positions in params, use that to construct fixes 2018-12-09 15:01:08 -08:00
Ng Zhi An
41613babd9 Prototype fix 2018-12-09 15:01:08 -08:00
Vidar Holen
cb57b4a74f Stable version 0.6.0
This release is dedicated to Factorio. If this is how much fun it is to
build factories and oppress natives, then history makes a lot of sense.
2018-12-02 19:08:06 -08:00
Vidar Holen
e3f0243c0e Add 'striptests' script to Cabal package 2018-12-02 19:08:06 -08:00
Vidar Holen
66b5f13c6f Make wiki links fit in 80 columns 2018-12-02 19:08:06 -08:00
Vidar Holen
a7a404a5a8 Fill in missing bits in CHANGELOG 2018-12-02 14:49:04 -08:00
Vidar Holen
0761f5c923 Merge pull request #1397 from ngzhian/man-en-dash
Disable smart typography extension for markdown input
2018-12-02 13:56:14 -08:00
Vidar Holen
b55149b22d Add man page instructions (fixes #1347) 2018-12-02 12:29:42 -08:00
Ng Zhi An
4097bb5154 Disable smart typography extension for markdown input
Fixes #1392
2018-11-29 23:18:20 -08:00
Vidar Holen
1b207b3d43 Preemptively fix possible '-- |' breakage 2018-11-26 20:43:15 -08:00
Vidar Holen
135b4aa485 Add stack builds to distro test 2018-11-26 20:41:29 -08:00
Vidar Holen
cb76951ad2 Add warnings for 'exit' similar to 'return' (fixes #1388) 2018-11-24 23:05:40 -08:00
Vidar Holen
705e476e4c Merge pull request #1389 from romanzolotarev/patch-1
Add OpenBSD to "Installing" section of README.md
2018-11-15 19:58:30 +11:00
Roman Zolotarev
e705552c97 Update README.html
Add OpenBSD to "Installing" section.
2018-11-15 08:49:26 +00:00
Vidar Holen
198aa4fc3d Merge pull request #1383 from l2dy/master
Fix typo in CHANGELOG
2018-11-08 11:13:55 +08:00
Zero King
f4044fbcc7 Fix typo in CHANGELOG 2018-11-08 03:07:52 +00:00
Vidar Holen
2827b35696 SC2240: Warn about . script args.. in sh/dash (fixes #1373) 2018-11-07 18:04:18 -08:00
Vidar Holen
de95c376ea Merge pull request #1380 from PeterDaveHello/Update-Dockerfile
Update Docker build-only image to Ubuntu 18.04
2018-11-08 08:34:21 +08:00
Peter Dave Hello
5e1b1e010a Update Docker build-only image to Ubuntu 18.04
Ref:
> Ubuntu 17.10 (Artful Aardvark) End of Life reached on July 19 2018
https://fridge.ubuntu.com/2018/07/19/ubuntu-17-10-artful-aardvark-end-of-life-reached-on-july-19-2018/
2018-11-02 13:47:22 +08:00
Vidar Holen
620c9c2023 Also warn about glob matching with [ a != b* ] (fixes #1374) 2018-11-01 04:47:44 -07:00
Vidar Holen
359b1467a2 Work around snap's old cabal + new snapcraft proxy. 2018-10-24 21:33:42 -07:00
Vidar Holen
df0a0d41fa Add SC1133: Warn when a line starts with |/||/&& (fixes #1359) 2018-10-21 17:46:46 -07:00
Vidar Holen
b815242506 Improve regex parsing (fixes #1367) 2018-10-21 15:25:35 -07:00
Vidar Holen
07b5aa2971 Add SC2239: shebang is not absolute path. 2018-10-17 20:38:21 -07:00
Oleg Grenrus
75949fe51e Change prop> to >>> prop $
As doctest doesn't make QuickCheck related magic, but only
evaluates expressions: We are fast.
2018-10-17 19:29:10 +03:00
Vidar Holen
f7b82658f4 Add $# to list of variables not containing spaces (fixes #1362) 2018-10-17 09:00:52 -07:00
Vidar Holen
e0e46e979a Add wiki links to output, and a -W controlling it. (Fixes #920) 2018-10-10 21:53:43 -07:00
Vidar Holen
79319558a5 Merge pull request #1350 from peti/master
Fix build with ghc 8.6.1
2018-10-04 20:11:40 -07:00
Vidar Holen
8d13add1ed Add automated cross-distro testing via Docker 2018-10-01 17:10:43 -07:00
Peter Simons
8940e60300 ShellCheck.cabal: our Setup.hs works fine with Cabal 2.4.x 2018-09-27 17:32:45 +02:00
Peter Simons
5f1c969546 getParentTree: avoid pattern matching in do notation
Pattern matching in "do" requires a MonadFail context, which we don't have in
pure code. Instead, we'll use "case-of" to bind the part of the state that
we're interested in.
2018-09-27 17:30:41 +02:00
Vidar Holen
dadfdfde97 Don't suggest subshells for cd ..; foo; cd.. 2018-09-21 21:08:41 -07:00
Vidar Holen
3e2cb26119 Add SC2238 about redirections to command names 2018-09-17 17:46:49 -07:00
Vidar Holen
1a6ae4f19e Add plug for shfmt 2018-09-16 10:56:53 -07:00
Vidar Holen
95a376aad1 Minor script cleanup 2018-09-16 10:11:03 -07:00
Vidar Holen
a06d7c1841 Merge pull request #1324 from ngzhian/679
Understand array variable declaration in read (fixes #679)
2018-09-15 12:33:58 -07:00
Vidar Holen
5202072a34 Add employer mandated disclaimer 2018-09-15 11:10:27 -07:00
Vidar Holen
72af1cfd59 Merge pull request #1331 from federicotdn/patch-1
Add link to flymake-shellcheck under Emacs section
2018-09-15 11:09:04 -07:00
Vidar Holen
228af7df54 Merge pull request #1337 from dimo414/master
Expand "rhs"; this abbreviation seems needlessly obfuscating.
2018-09-12 16:01:43 -07:00
Michael Diamond
6db392511b Expand "rhs"; this abbreviation seems needlessly obfuscating. 2018-09-12 14:22:40 -07:00
Oleg Grenrus
d510a3ef6c Guard quickcheck.1 regeneration
Without this guard it will be regenerate on each run,
and cabal new-build considers whole package dirty.
2018-09-10 19:44:06 +03:00
Oleg Grenrus
5516596b26 Fix quicktest, add note to it and quickrun 2018-09-10 19:41:15 +03:00
Oleg Grenrus
9e7539c10b Use native codegen in docker build, results in smaller binary 2018-09-10 19:09:28 +03:00
Oleg Grenrus
a5a7b332f1 Use LLVM + split-sections 2018-09-10 19:09:28 +03:00
Oleg Grenrus
a68e3aeb26 Striptests is not necessary anymore 2018-09-10 19:09:28 +03:00
Oleg Grenrus
259b1a5dc6 Run tests as doctests 2018-09-10 19:09:28 +03:00
Ng Zhi An
07f04e13ce Understand array variable declaration in read (fixes #679 fixes #1272)
It used to only treat all trailing variables in read as varaible
declarings, but an array variable can be declared in other positions:

    read -a foo -r

foo is a declared variable, and multiple such variables can be declared.
2018-09-08 09:19:02 -07:00
Federico T
493ecd6f73 Add link to flymake-shellcheck under Emacs section
I've recently created the flymake-shellcheck package for Emacs, which allows using ShellCheck with the built-in Flymake package.
2018-09-07 12:37:16 -03:00
Vidar Holen
f0a2e688c4 Don't warn about LINENO since it's now POSIX. Fixes #644 2018-09-03 12:36:25 -07:00
Vidar Holen
0cee8a993d Suggest reading the wiki page in the issue template 2018-08-28 20:40:57 -07:00
Vidar Holen
3d03b0ab3b Suggest -z/-n instead of ! -n/-z (fixes #1326). 2018-08-28 20:15:54 -07:00
Vidar Holen
488d6dcb41 Improve find leading flag detection (fixes #1312) 2018-08-26 18:18:57 -07:00
Vidar Holen
d02a9bbcce Account for &&/||/{}/() in SC2233&co (fixes #1320). 2018-08-26 17:36:10 -07:00
Vidar Holen
165e408114 Merge branch 'ngzhian-opqaque-interface' 2018-08-18 20:33:14 -07:00
Vidar Holen
932e2b3538 Merge branch 'opqaque-interface' of https://github.com/ngzhian/shellcheck into ngzhian-opqaque-interface 2018-08-18 20:32:27 -07:00
Vidar Holen
76b1482f64 Avoid using error for option parsing failure 2018-08-18 20:06:44 -07:00
Vidar Holen
49250eadae Add --severity to CHANGELOG 2018-08-18 20:06:31 -07:00
Martin Schwenke
3fe11927bb SQUASH: --severity specifies *minimum* severity to be handled
Signed-off-by: Martin Schwenke <martin@meltin.net>
2018-08-18 20:05:56 -07:00
Martin Schwenke
b16da4b242 Add command-line option -S/--severity
Specifies the maximum severity of errors to handle.  For example,
specifying "-S warning" means that errors of severity "info" and
"style" are ignored.

Signed-off-by: Martin Schwenke <martin@meltin.net>
2018-08-18 20:05:56 -07:00
Ng Zhi An
c8e0797350 Make data in Interface more opaque 2018-08-17 22:10:18 -07:00
Vidar Holen
15aaacf715 Add test for parsing bitwise not 2018-08-15 18:30:10 -07:00
Vidar Holen
5ef4229f61 Modernize SC2028 echo escape test 2018-08-07 19:31:28 -07:00
Vidar Holen
afada43978 Merge pull request #1311 from ngzhian/1310
Use regex to match special flags for printf
2018-08-07 18:45:44 -07:00
Ng Zhi An
8be76b13b9 Use regex to match special flags for printf
Fixes #1310
2018-08-05 22:45:24 -07:00
Vidar Holen
581be5878b Suggest 'cat' when piping/redirecting to echo (fixes #1292) 2018-07-28 17:38:53 -07:00
Vidar Holen
0f835a5a2c Don't trigger SC2222 for fallthrough case branches (fixes #1044) 2018-07-28 12:30:06 -07:00
Vidar Holen
4b0a35d4c9 Merge pull request #1302 from pjeby/fix949
Fix #949 (failing on @ in function names)
2018-07-26 21:07:48 -07:00
Vidar Holen
51e0c1be62 Use three instead of two dots in 2006 message 2018-07-26 19:59:42 -07:00
Vidar Holen
d8a32da07f Retire SC1117 (unknown quoted escapes) due to noise 2018-07-26 19:23:53 -07:00
PJ Eby
0d1a34a291 Fix #949 (failing on @ in function names)
'@' was previously mentioned in 5005dc0fa1 as a
character needed to fix #909, but was not included
in the actual change at that time.
2018-07-23 16:18:35 -04:00
Vidar Holen
5005dc0fa1 Allow directive/-s to override shebang blacklist (fixes #974) 2018-07-22 12:43:51 -07:00
Vidar Holen
b8ee7436e5 Add a test for 03ce3b15 2018-07-21 13:51:21 -07:00
Vidar Holen
da8e450386 Realign =s 2018-07-21 13:51:08 -07:00
Vidar Holen
c3ac4c3d87 Merge pull request #1298 from ngzhian/1268
Fix false positive when indexing into array in cond
2018-07-21 13:43:45 -07:00
Ng Zhi An
03ce3b15b6 Fix false positive when indexing into array in cond
Fixes #1268
2018-07-18 22:31:58 -07:00
Vidar Holen
10edba3ab8 Minimize build size with -Os and -split-sections 2018-07-12 09:33:59 -07:00
Vidar Holen
797b424917 Add armv6hf link for Raspberry Pi 2018-07-08 20:47:05 -07:00
Vidar Holen
84e678e9ff TravisCI armv6hf build (aka Raspberry Pi build) 2018-07-08 20:13:33 -07:00
Vidar Holen
3a672968f3 Merge pull request #1282 from kenden/patch-1
Add instructions to install linux binary
2018-07-07 13:32:37 -07:00
Quentin Nerden
8c7efae393 Add instructions to install linux binary 2018-07-05 15:30:16 +02:00
Vidar Holen
f91b5bc270 Merge pull request #1256 from ngzhian/mv-stdin
Do not warn on mv -i (fixes #1251)
2018-06-24 11:47:53 -07:00
Vidar Holen
b01f1128c7 Make SC1012 "printf '\t'" suggestion use single quotes 2018-06-24 11:47:00 -07:00
Vidar Holen
db33294838 Merge pull request #1257 from ngzhian/trailing-comma-exclude
Allow trailing comma in exclude flag
2018-06-24 11:46:26 -07:00
Vidar Holen
75fb4da387 Don't warn about tr '[=e=]' equivalence classes 2018-06-23 16:55:35 -07:00
Vidar Holen
366262af18 Update CHANGELOG to mention end positions 2018-06-23 16:53:44 -07:00
Vidar Holen
6869c2fa18 Merge pull request #1261 from ngzhian/1188
Do not warn find --help (fixes #1188)
2018-06-23 16:07:23 -07:00
Vidar Holen
868a7be33e Improve spans for some warnings 2018-06-17 19:19:18 -07:00
Vidar Holen
7138abff4b Expose (some) span information in TTY output 2018-06-17 17:44:31 -07:00
Vidar Holen
9d3e79b576 Require all Ids to be constructed with a span 2018-06-16 17:33:08 -07:00
Vidar Holen
402e635f86 Warn about & followed by letters, e.g. http://foo/?a=b&c=d 2018-06-16 12:30:19 -07:00
Ng Zhi An
91cbcddd9d Do not warn find --help (fixes #1188) 2018-06-14 22:40:26 -07:00
Ng Zhi An
963b39b002 Allow trailing comma in exclude flag 2018-06-13 22:31:51 -07:00
Ng Zhi An
0cc45447d3 Do not warn on mv -i (fixes #1251) 2018-06-13 21:39:37 -07:00
Vidar Holen
32a53f21b5 Merge pull request #1239 from ngzhian/end_column
End column
2018-06-13 19:29:55 -07:00
Vidar Holen
12b8720bd8 Merge pull request #1255 from ngzhian/popd-n
Check popd flags for -n (fixes #1252)
2018-06-13 19:22:39 -07:00
Ng Zhi An
7adeaccd11 Check popd flags for -n (fixes #1252) 2018-06-12 22:53:41 -07:00
Ng Zhi An
b63483d44c Remove unused import 2018-06-12 22:50:02 -07:00
Ng Zhi An
4111ce8fde Make end pos non-optional 2018-06-12 22:39:06 -07:00
Ng Zhi An
b9a9eb2529 Change getNextId to create a zero width span at new id 2018-06-12 22:17:35 -07:00
Ng Zhi An
e717802de1 Change usage of endPosOfStartId to startSpan and endSpan 2018-06-12 22:11:11 -07:00
Ng Zhi An
1699c9e9ba Add api to begin and end a span of source code 2018-06-12 21:56:53 -07:00
Vidar Holen
bfc32200e2 Correctly consider $'..' a literal (fixes #1242) 2018-06-10 20:23:10 -07:00
Vidar Holen
52e8a42d9d Merge pull request #1253 from sblondon/master
Remove unnecessary dot
2018-06-09 13:03:24 -07:00
sblondon
00360af672 Remove unnecessary dot
The dot after the screenshot is strange so this commit remove it.
2018-06-08 10:57:41 +02:00
Ng Zhi An
8ff35fb4af Add end pos to readSingleQuoted 2018-06-07 23:09:59 -07:00
Ng Zhi An
29e8c0a16e Add end pos to readDollarBraced 2018-06-07 22:25:16 -07:00
Ng Zhi An
3848788c2d Add end pos to readDollarVariable 2018-06-07 21:55:41 -07:00
Ng Zhi An
0c459ae2cb Add function to set end pos of start id 2018-06-07 21:55:41 -07:00
Ng Zhi An
e496b413bd Remove usage of withNextId 2018-06-07 21:55:41 -07:00
Ng Zhi An
48ac654a93 Merge end pos map into start pos map 2018-06-07 21:55:41 -07:00
Russell Harmon
4470fe715c Support emitting a correct end column on SC2086
This does the necessary work to emit end columns on AST analyses. SC2086
is made to emit a correct end column as an illustrative example.

For example:
```
$ shellcheck -s bash -f json /dev/stdin <<< 'echo $1'
[{"file":"/dev/stdin","line":1,"endLine":1,"column":6,"endColumn":8,"level":"info","code":2086,"message":"Double quote to prevent globbing and word splitting."}]
```

This change deprecates the parser's getNextId and getNextIdAt, replacing
it with a new withNextId function. This function has the type signature:

withNextId :: Monad m => ParsecT s UserState (SCBase m) (Id -> b) -> ParsecT s UserState (SCBase m) b

Specifically, it should be used to wrap read* functions and will pass in
a newly generated Id which should be used to represent that node.
Sub-parsers will need their own call to withNextId in order to get a
unique Id.

In doing this, withNextId can now track both the entry and exit position
of every read* parser which uses it, enabling the tracking of end
columns throughout the application.
2018-06-07 21:55:41 -07:00
Vidar Holen
379321d1f3 Show tags in travis output 2018-06-07 20:40:44 -07:00
Vidar Holen
0adea473fd Update CHANGELOG after release 2018-06-07 20:19:00 -07:00
Vidar Holen
a3be776f80 Stable version 0.5.0
This release is dedicated to Valve for keeping PC gaming awesome.
Also, for that time they proved the need for a tool like ShellCheck.
2018-05-31 20:01:42 -07:00
Vidar Holen
b5e5d249c4 Merge pull request #1237 from ngzhian/1234
Check if builtin cd is called
2018-05-27 18:34:18 -07:00
Vidar Holen
efffc6150b Warn about string operations on $@/$* (fixes #1236) 2018-05-27 12:53:01 -07:00
Ng Zhi An
cb4a0c0250 Check if builtin cd is called
Fixes #1234
2018-05-27 11:42:37 -07:00
Vidar Holen
135cf5932f Parse here docs as per spec (fixes #1050) 2018-05-26 21:01:18 -07:00
Vidar Holen
467dfe07b6 Add a unit test and separate ids for 884eff0c 2018-05-23 19:51:36 -07:00
Vidar Holen
d140388bea Merge pull request #1232 from ngzhian/source-x
Add T_SourceCommand to wrap source commands and sourced code
2018-05-23 19:41:55 -07:00
Ng Zhi An
884eff0c36 Add T_SourceCommand to wrap source commands and sourced code
Fixes #1181
2018-05-22 22:43:26 -07:00
Vidar Holen
1d8047cce1 Warn about unnecessary subshells in tests 2018-05-22 22:35:37 -07:00
Vidar Holen
77546fba2f Merge pull request #1223 from ngzhian/1124
Handle offset references of the form [foo]:bar (fixes #1124)
2018-05-20 17:26:08 -07:00
Vidar Holen
4a5ee06ce4 Merge pull request #1206 from ngzhian/aeson
Change to aeson (fixes #1085)
2018-05-20 17:19:20 -07:00
Ng Zhi An
4dceecb1ed Handle offset references of the form [foo]:bar (fixes #1124) 2018-05-13 22:48:02 -07:00
Vidar Holen
5b226e733b Merge pull request #1203 from ngzhian/1199
Whitelist rename for SC2016 (fixes #1199)
2018-05-13 16:56:09 -07:00
Vidar Holen
46c10c1571 Merge branch 'master' into 1199 2018-05-13 16:55:53 -07:00
Vidar Holen
1de8ba0210 Merge pull request #1208 from ngzhian/1186
Add unset to list of commands exempt from 2016
2018-05-13 16:47:29 -07:00
Vidar Holen
407f6a63b9 Merge branch 'master' into 1186 2018-05-13 16:47:18 -07:00
Vidar Holen
7ee7448a70 Merge pull request #1221 from ngzhian/1192
Assignments are okay in SC2094 (fixes #1192)
2018-05-13 16:44:11 -07:00
Vidar Holen
48ebd41e22 Merge pull request #1222 from ngzhian/196
Suppress SC2016 for git filter-branch (fixes #196)
2018-05-13 15:45:20 -07:00
Ng Zhi An
0c88fbc76d Suppress SC2016 for git filter-branch (fixes #196) 2018-05-13 15:18:55 -07:00
Ng Zhi An
b3362f1dc3 Assignments are okay in SC2094 (fixes #1192) 2018-05-13 15:17:32 -07:00
Ng Zhi An
2c6bc43614 Add Data.Monoid 2018-05-13 11:44:21 -07:00
Vidar Holen
235bf6605f Merge pull request #1205 from ngzhian/remove-unused
Remove unused code
2018-05-12 19:15:42 -07:00
Vidar Holen
7029a713c7 Merge pull request #1207 from ngzhian/1184
When given a %* format string, expect one more argument
2018-05-12 18:50:23 -07:00
Vidar Holen
cf608dc2f6 Parse FD move operations like 2>&1- correctly. Fixes #1180. 2018-05-12 18:30:35 -07:00
Vidar Holen
aa3b3fdc56 Make .ghci look in ./src 2018-05-12 17:47:21 -07:00
Vidar Holen
bca2ad4e18 Don't think declare -x -F var is used (fixes #1209). 2018-05-12 17:34:23 -07:00
Vidar Holen
719e1854e5 Clarify 'export' suggestion in SC2034 (unused vars). 2018-05-11 21:39:54 -07:00
Ng Zhi An
20ad7dc8de Add unset to list of commands exempt from 2016
Fixes #1186
2018-05-06 16:45:57 -07:00
Ng Zhi An
f84859ab90 When given a %* format string, expect one more argument
Fixes #1184
2018-05-06 16:39:51 -07:00
Ng Zhi An
08235a1cb2 Change to aeson (fixes #1085)
Adds bytestring as a dependency for putStrLn encoded values.
2018-05-06 16:07:53 -07:00
Ng Zhi An
728922d2b8 Remove unused code 2018-05-06 15:24:34 -07:00
Ng Zhi An
a953dd3454 Whitelist rename for SC2016 (fixes #1199) 2018-05-06 10:28:17 -07:00
Vidar Holen
ef6a5b97b9 Refactor sudo checks into CommandChecks 2018-04-30 22:59:23 -07:00
Vidar Holen
8873a1732b Merge pull request #1195 from sdknudsen/master
Warn about invalid arguments to sudo
2018-04-30 21:50:28 -07:00
Stefan Knudsen
5adfce72e1 Warn about invalid arguments to sudo 2018-04-29 01:16:31 -04:00
Vidar Holen
12b3fdf661 Update gallery of bad code 2018-04-28 12:58:44 -07:00
Vidar Holen
bb4ce86fab Account for array index in SC2154 ${var:?} (fixes #1166) 2018-04-28 12:09:54 -07:00
Vidar Holen
7ec2fa2d3e Remove 'nice' from list of non-reading commands (fixes #1169) 2018-04-28 11:39:42 -07:00
Vidar Holen
5481ccd7f7 Warn about elseif or elsif as command names (fixes #1177) 2018-04-27 22:23:37 -07:00
Vidar Holen
a1d8947297 Fix broken test stripping 2018-04-22 14:57:43 -07:00
Vidar Holen
683a30abde Merge pull request #1174 from rasa/patch-1
Added scoop install
2018-04-22 14:13:35 -07:00
Vidar Holen
573936f353 Merge pull request #1185 from 0mp/master
Add FreeBSD installation instructions
2018-04-22 14:10:59 -07:00
Vidar Holen
ce7658ed86 Merge pull request #1168 from vmchale/master
Bump to ghc 8.4.1
2018-04-22 14:10:25 -07:00
Mateusz Piotrowski
0136d9ccce Add FreeBSD installation instructions 2018-04-19 13:25:25 +02:00
Ross Smith II
a4c6cea5e6 Added scoop install
See https://github.com/lukesampson/scoop/blob/master/bucket/shellcheck.json
2018-04-07 16:22:29 -07:00
Vidar Holen
32af2783f0 Allow stripping unit tests 2018-04-02 21:14:23 -07:00
Vanessa McHale
08aab3c161 hlints 2018-04-02 11:48:21 -05:00
Vanessa McHale
cf39adff75 bump to latest ghc 2018-04-02 11:44:18 -05:00
Vidar Holen
da4072a118 Blacklist base 4.6.0.1 to disable GHC 7.6.3 (#1131) 2018-03-29 21:41:00 -07:00
Vidar Holen
08d2eef411 Whitelist docker for SC2016 about '$var'. Fixes #1161 2018-03-29 19:27:34 -07:00
Vidar Holen
de257a6cf3 Merge pull request #1164 from Lin-Buo-Ren/improve-snap-package
Improve snap packaging
2018-03-29 11:49:26 -07:00
林博仁(Buo-Ren Lin)
68c24925bc Add info on connecting to removable-media interface in snap description
Signed-off-by: 林博仁(Buo-Ren Lin) <Buo.Ren.Lin@gmail.com>
2018-03-29 23:47:59 +08:00
林博仁(Buo-Ren Lin)
366dc5d3f8 Add snap install instructions to README
Currently shellcheck is only provided by the edge channel, should remove the --channel argument after it is in candidate/stable.

Signed-off-by: 林博仁(Buo-Ren Lin) <Buo.Ren.Lin@gmail.com>
2018-03-29 20:24:31 +08:00
林博仁(Buo-Ren Lin)
1ed743e410 Add snapcraft generated files to the Git tracking ignore rules
This patches uses the following gitignore syntax so that only entries in the root folder is ignored, it is suggested to apply it to existing rules as well.

```
A leading slash matches the beginning of the pathname. For
example, "/*.c" matches "cat-file.c" but not
"mozilla-sha1/sha1.c".
```

Refer-to: gitignore(5) manpage
Signed-off-by: 林博仁(Buo-Ren Lin) <Buo.Ren.Lin@gmail.com>
2018-03-29 20:05:52 +08:00
林博仁(Buo-Ren Lin)
9a2aad16ad Add removable-media plug so that scripts in removable media can be checked
Otherwise it will be blocked by Apparmor with the following message:

```
$ shellcheck script
audit: type=1400 audit(TIMESTAMP): apparmor="DENIED" operation="open" profile="snap.shellcheck.shellcheck" name=2F6D656469612F4C696E2D42756F2D52656E2F57696E646F7773205553422F717569636B72756E pid=10175 comm="shellcheck" requested_mask="r" denied_mask="r" fsuid=FSUID ouid=OUID
script: script: openBinaryFile: permission denied (Permission denied)
```

NOTE:

* This plug is not Auto-connect plug, it has to be manually connected by user with `snap connect shellcheck:removable-media :removable-media`
* Currently files under /mnt is not checkable as snapd doesn't provide an interface for it for now.

Refer-to: Interfaces reference - Snaps are universal Linux packages <https://docs.snapcraft.io/reference/interfaces>
Signed-off-by: 林博仁(Buo-Ren Lin) <Buo.Ren.Lin@gmail.com>
2018-03-29 20:00:23 +08:00
Vidar Holen
177cb10daa Enable strict mode with home access 2018-03-28 18:26:16 -07:00
Vidar Holen
4aca1ff128 Warn when printf arg count is not a multiple of format count 2018-03-28 08:57:38 -07:00
Vidar Holen
ffed7caff4 quickrun script now works with new source layout 2018-03-28 08:57:38 -07:00
Vidar Holen
ef28200199 Merge pull request #1159 from geirha/patch-1
Consider type a valid command in sh
2018-03-27 11:38:07 -07:00
Geir Hauge
55216792c9 Consider type a valid command in sh
[type](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/type.html) *is* defined by POSIX, and even the bourne shell has the `type` command.
2018-03-25 12:11:57 +02:00
Vidar Holen
51e115cf47 Attempt to fix snap build 2018-03-24 17:43:32 -07:00
Vidar Holen
764b242f1b Suggest quoting expansions in for loop globs 2018-03-24 17:43:20 -07:00
Vidar Holen
c3b606c68a Encourage users to use stable rather than latest 2018-03-21 17:55:21 -07:00
Vidar Holen
9f53109dfa Fix tagging of 'stable' 2018-03-21 17:54:36 -07:00
Vidar Holen
795a881219 Fix docker image workdir and add test 2018-03-21 09:39:06 -07:00
Vidar Holen
6dd5350e3b Merge pull request #1143 from pratikmallya/simplify_dockerbuild
Simplify Dockerfile
2018-03-20 22:31:36 -07:00
Vidar Holen
a5b359591c Merge branch 'master' into simplify_dockerbuild 2018-03-20 22:31:21 -07:00
Vidar Holen
966194e387 Merge branch 'pratikmallya-simplify_dockerbuild' 2018-03-20 22:10:24 -07:00
Vidar Holen
71bcc80c2f Allow more Docker build caching 2018-03-20 22:09:13 -07:00
Vidar Holen
48616225b3 Merge pull request #1147 from tdmalone/patch-1
README - Travis script for updating shellcheck ver
2018-03-20 19:28:39 -07:00
Tim Malone
99276cb9f5 README - Travis script for updating shellcheck ver
Shellcheck in default Travis builds is currently a version behind
2018-03-19 11:15:28 +11:00
Pratik Mallya
f769d4e92c Add TravisCI Build Status file 2018-03-15 23:13:54 -05:00
Pratik Mallya
71df01c00f Simplify Dockerfile
Use multi stage Dockerfile to greatly simplify build.
2018-03-15 23:12:28 -05:00
Vidar Holen
5364701914 Merge branch 'simplify_dockerbuild' of https://github.com/pratikmallya/shellcheck into pratikmallya-simplify_dockerbuild 2018-03-15 09:53:50 -07:00
Vidar Holen
fb97aca5a6 Merge pull request #1140 from phadej/src
Move library into src/
2018-03-15 16:52:26 +00:00
Pratik Mallya
6b81a9924c Simplify Dockerfile
Use multi stage Dockerfile to greatly simplify build.
2018-03-14 21:43:34 -05:00
Oleg Grenrus
cd7c077ecc Move library into src/ 2018-03-08 19:57:40 +02:00
Oleg Grenrus
b33607b048 Add custom-setup stanza and containers lowerbound
custom-setup:

- http://cabal.readthedocs.io/en/latest/developing-packages.html#custom-setup-scripts
- https://www.well-typed.com/blog/2015/07/cabal-setup-deps/

Bounds:
- containers-0.5 is required if Data.Map.Strict
- parsec-3.0 for Text.Parsec
- json-0.3.6 for makeObj
2018-03-08 19:35:50 +02:00
Vidar Holen
969230f171 MacPorts version appears unmaintained. Remove from docs. 2018-03-08 08:48:03 -08:00
Vidar Holen
a98d69f4ff Update CHANGELOG with $var[ and here doc expansion fixes 2018-03-04 15:42:52 -08:00
Vidar Holen
f71c142a44 Don't ignore parse failures in here documents. Fixes #1135. 2018-03-04 15:24:04 -08:00
Vidar Holen
9dfcf54f10 Functionality for emitting parse errors but still continue 2018-03-04 14:42:47 -08:00
Vidar Holen
c8cd9dd09c Add a debugParseScript for development 2018-03-03 15:36:50 -08:00
Vidar Holen
8b8aeb4409 Rephrase SC2069 (cmd 2>&1 > file) and make it a warning. Fixes #633 2018-03-03 13:33:24 -08:00
Vidar Holen
ee354ffce8 POSIX warning for export -[^p]. Fixes #1130. 2018-02-27 20:38:02 -08:00
Vidar Holen
9fc3ddf849 Fix SC1087 to trigger on any $var[, not just $var[@] 2018-02-25 18:25:47 -08:00
Vidar Holen
ecb9d07f52 Update changelog with associative arrays in (()) fix 2018-02-25 18:15:55 -08:00
Vidar Holen
d16bf41c3d Better support arrays in arithmetic contexts. Fixes #1074 2018-02-25 18:08:38 -08:00
Vidar Holen
8d5e3a80ae Merge pull request #1123 from jonhiggs/check-for-which-usage
Check for calls to `which`.
2018-02-25 17:08:37 -08:00
Vidar Holen
34e0fa53c8 Merge pull request #1125 from jonhiggs/nextnumber-macos-support
MacOS support for nextnumber
2018-02-25 17:08:15 -08:00
Jon Higgs
7fb27310e1 Rely upon /usr/bin/env to find bash
This allows you to use the homebrew install Bash 4 on MacOS systems. It
should compatible with most if not all modern Linux distros.
2018-02-26 11:24:09 +11:00
Jon Higgs
00d3c09ddb Raise error unless interpreter supports globstar 2018-02-26 11:23:42 +11:00
Jon Higgs
e8fc09414a Check for calls to which.
Favour the builtin `command -v` instead.
2018-02-26 10:00:25 +11:00
Vidar Holen
b7a8b090d2 SC2229: Warn about 'read $var' 2018-02-25 13:47:58 -08:00
Vidar Holen
72044a79c6 Update changelog 2018-02-25 13:47:58 -08:00
Vidar Holen
6511dc0246 Add missing import 2018-02-25 13:29:06 -08:00
Vidar Holen
740441f2c4 Merge pull request #1121 from PeterDaveHello/update-travis-ci-doc
[Docs] Update Travis CI part in README.md
2018-02-25 11:37:00 -08:00
Peter Dave Hello
b311563421 Update Travis CI part in README.md 2018-02-20 04:52:12 +08:00
Vidar Holen
6d257bfa17 Warn about 'while!' and 'while:' 2018-02-17 21:58:29 -08:00
Vidar Holen
d8717c7046 s/parser error/syntax error/g 2018-02-17 17:18:05 -08:00
Vidar Holen
7aa3a7ffc3 Improve message for SC2163 (export $var). Helps #1117 2018-02-17 17:12:11 -08:00
Vidar Holen
017af8333f Merge pull request #1112 from Nightfirecat/sc2154-local-test
Add test for `local` keyword in SC2154
2018-02-10 08:04:07 -08:00
Jordan Atwood
f73d6f2332 Add test for local keyword in SC2154
Follow-up to koalaman/shellcheck#988
2018-02-07 17:50:55 -08:00
koalaman
a840f4e464 Merge pull request #1100 from mkhl/SC2029
SC2029: Skip when there are options to ssh
2018-01-24 19:38:38 -08:00
Vidar Holen
0f5e40c076 Mention shellcheck-static for Arch 2018-01-24 09:02:56 -08:00
Martin Kühl
ccaacb108a SC2029: Skip when there are options to ssh
Fixes #327

SC2029 generates false positives when given an ssh command that includes
options with arguments because it assumes the first non-option must be
the host:port argument and the last argument is a command to run.
As suggested the comments on #327, this change fixes those by skipping
the check when there are any options present.
2018-01-24 13:05:22 +01:00
Martin Kühl
56751413b4 SC2029: Add false positive test
This change adds a test case for a valid command that gets falsely
flagged with SC2029.
2018-01-24 13:04:26 +01:00
Vidar Holen
ba5f20deda Fix parsing of escaped chars in regex groups. Fixes #1077 2018-01-21 16:13:16 -08:00
Vidar Holen
c86885427c Warn about comments/blanks before shebang. Fixes #844 2018-01-21 13:57:44 -08:00
Vidar Holen
7b3c4025fb Warn about redirs in the middle of 'find' commands. Fixes #405 2018-01-21 11:12:22 -08:00
Vidar Holen
3b004275cf Add unit test for issue #1091 2018-01-20 11:42:31 -08:00
koalaman
72971fa52b Merge pull request #1097 from sdknudsen/fix/recognize-ids-with-underscores
Use readVariableName combinator
2018-01-20 11:35:22 -08:00
Stefan Knudsen
dbdab5705f Use readVariableName combinator 2018-01-19 16:19:06 -05:00
Vidar Holen
46a3019ed7 Fix annotations for here documents (fixes #1071) 2018-01-17 19:20:10 -08:00
Vidar Holen
81978d15bd Remove unused here doc boundary concept. 2018-01-17 18:48:17 -08:00
Vidar Holen
1d0db9267d Mention SC2224-6 about mv/cp/ln without destination 2018-01-17 18:32:07 -08:00
Vidar Holen
a6fb9d1ef8 Warn about C-style comments 2018-01-17 18:14:36 -08:00
Vidar Holen
dc1e7c1bd4 Make docker image shellcheck-alpine behave more like alpine. 2018-01-14 18:01:18 -08:00
Vidar Holen
5b14dba489 Parse 'else if' correctly, and not like elif. Fixes #1088. 2018-01-13 22:42:19 -08:00
koalaman
ee997fdec4 Merge pull request #1093 from albertodonato/snap-package
Add snapcraft.yaml to build snap package
2018-01-13 19:36:06 -08:00
koalaman
1badeff383 Merge pull request #1092 from etam/patch-1
Update openSUSE instruction
2018-01-13 19:33:18 -08:00
Vidar Holen
2d5ed23ca1 Warn about cp/mv/ln with a single argument. Fixes #1080. 2018-01-13 16:44:58 -08:00
Alberto Donato
ec581cee90 Add snapcraft.yaml to build snap package 2018-01-13 00:31:26 +01:00
Adam Mizerski
bb32289ee3 Update openSUSE instruction
Package is main repo of all versions. No need to add repository.
2018-01-11 18:51:39 +01:00
Vidar Holen
31d6b063d9 Improve indented here doc token message. 2018-01-10 21:12:22 -08:00
Vidar Holen
3c5c74ff04 Add quote warning specific to : ${var=val}. Fixes #1084 2018-01-06 10:53:53 -08:00
koalaman
9657e8dda3 Merge pull request #1078 from CyberShadow/pull-20171221-031403
Extend SC2216/SC2217 with 'true' and 'false'
2017-12-20 20:44:06 -08:00
Vladimir Panteleev
6ed60b403f Extend SC2216/SC2217 with 'true' and 'false' 2017-12-21 03:29:17 +00:00
koalaman
8fa8823981 Merge pull request #1072 from vapier/master
convert http:// URIs to https://
2017-12-14 09:35:57 -08:00
Mike Frysinger
161801a86e convert http:// URIs to https://
Also update the ShellCheck homepage to the new dedicated domain.
2017-12-14 01:06:43 -05:00
Vidar Holen
c36f6d89ba Stable version 0.4.7
This release is dedicated to net neutrality. Remember when the Internet
was a meritocracy? [Please drink a verification can to continue.]
2017-12-08 20:29:12 -08:00
Vidar Holen
e801da0621 Add a changelog 2017-12-07 17:49:43 -08:00
koalaman
51e6bf809f Merge pull request #1041 from LukeShu/fix-isClosingFileOp
Fix isClosingFileOp (fixes issue #862)
2017-11-08 10:15:21 -08:00
Vidar Holen
3413a076ff Cabal: Don't make executables depend on library 2017-11-05 20:51:39 -08:00
Vidar Holen
53f63b85bb Use Data.Map.Strict instead of Map.insertWith' 2017-11-05 20:11:04 -08:00
Luke Shumaker
df068bc8ed Fix isClosingFileOp (fixes issue #862)
The isClosingFileOp function expected closing file ops to use T_IoFile, but
they actually use T_IoDuplicate; so it effectively always returned False.
2017-11-05 18:53:01 -05:00
Vidar Holen
102683ab04 Try to warn when using directives after commands (#981) 2017-11-04 15:22:17 -07:00
Vidar Holen
acead72c93 Improve directive parsing 2017-10-29 17:39:13 -07:00
Vidar Holen
0c1e2bbd4d Warn when using directives in front of elif and case items (#1036) 2017-10-29 16:31:46 -07:00
koalaman
5d9cb81008 Merge pull request #1026 from PeterDaveHello/patch-1
Enable syntax highlight in README.md code block
2017-10-15 19:09:32 -07:00
koalaman
1491402dcb Merge pull request #1027 from PeterDaveHello/README.md-Table-of-Contents
Add Table of Contents in README.md
2017-10-15 19:08:16 -07:00
Vidar Holen
436a46ebab Improve automated docker builds and tagging 2017-10-15 15:43:06 -07:00
Vidar Holen
db1e24d140 Dockerfile renamed "shellcheck" to "bin". Unbreak it. 2017-10-10 10:02:11 -07:00
Peter Dave Hello
35daf7534b Add Table of Contents in README.md 2017-10-10 20:25:04 +08:00
Peter Dave Hello
76ad5dbb9f Enable syntax highlight in README.md code block 2017-10-10 20:20:51 +08:00
Vidar Holen
f73736e5c9 Add Alpine-based docker image 2017-10-07 15:19:35 -07:00
Vidar Holen
3785a08906 Don't suggest $@ in [[ $* = "" ]] (#976) 2017-10-01 10:27:21 -07:00
Vidar Holen
74c199b51a Warn when one case pattern overrides another. 2017-09-16 15:23:51 -07:00
Vidar Holen
371dcdda3a Warn about missing default case for getopts. 2017-09-16 10:26:28 -07:00
Vidar Holen
38044e3f75 Fix 2062 for grep -e -foo bar* and --regex -foo bar* 2017-09-09 17:03:29 -07:00
Vidar Holen
b0f6f935f3 Don't suggset quoting in grep -- -foo bar* (#517) 2017-09-09 16:57:06 -07:00
Vidar Holen
bd2facb245 Suggest (( expr )) over let expr (#813) 2017-09-09 16:07:38 -07:00
Vidar Holen
895ba31337 Add ^@![]/ to allowed function characters (#909) 2017-09-09 15:34:08 -07:00
koalaman
ccc037d458 Merge pull request #988 from Nightfirecat/953-local-A-fix
SC2154: Fix false positive on `local`
2017-09-09 09:37:04 -07:00
koalaman
a1b370efbc Merge pull request #983 from Dynamic-Gravity/master
Updated readme installation instructions
2017-09-09 09:35:59 -07:00
Jordan Atwood
7f36c369f3 SC2154: Fix false positive on local 2017-09-06 15:40:31 -07:00
Unknown
7b55e73e03 Updated readme installation instructions
Added installation instructions for Solus distro.
2017-08-29 13:38:12 -04:00
Vidar Holen
6c068e7d29 Merge branch 'master' of github.com:koalaman/shellcheck 2017-08-13 19:45:31 -07:00
Vidar Holen
8dd40efb44 Add support for -a: emit for sourced files. 2017-08-13 19:34:45 -07:00
koalaman
751aebf984 Merge pull request #968 from ssbarnea/patch-1
Documented binary cabal install for MacOS
2017-08-13 10:52:03 -07:00
Sorin Sbarnea
3bf6913a15 Documented binary cabal install for MacOS
Installing haskell binaries is 50x faster than compiling it from source.
2017-08-11 12:01:28 +01:00
Vidar Holen
73d06c4f47 Autogenerate list of formats for --help 2017-08-06 15:48:59 -07:00
koalaman
72ed234291 Merge pull request #964 from blueyed/help-document-output-formats
List available output formats in --help output
2017-08-06 15:35:26 -07:00
koalaman
b94c03e5a1 Merge pull request #957 from martin-schwenke/issue-950
Fix incorrect detection of bash-style substring expansion (issue #950)
2017-08-06 15:34:23 -07:00
Daniel Hahler
226bc4409c Use spaces with list of dialects in --help for consistency 2017-08-06 16:25:31 +02:00
Daniel Hahler
4a6acb6ff0 List available output formats in --help output 2017-08-06 16:24:43 +02:00
koalaman
1d76abc439 Add storage bucket listing to readme 2017-07-30 10:52:06 -07:00
Martin Schwenke
807d899f3b Fix incorrect detection of bash-style substring expansion
Substring expansion detection only considers ':' as a separator..  It
needs to avoid triggering for ":-", ":=", ":+" and ":?", since they
mean other things.

This is a regression introduced by commit
a90b6d14b3

Signed-off-by: Martin Schwenke <martin@meltin.net>
2017-07-20 15:59:05 +10:00
koalaman
d6803ffa24 Merge pull request #955 from tsoernes/patch-1
Add Stack as install method
2017-07-18 20:39:39 -07:00
tsoernes
4ec8d73a14 Add Stack as install method 2017-07-19 04:17:09 +02:00
Vidar Holen
81388cefd2 Warn when calling functions before defining them. 2017-07-10 22:53:26 -07:00
Vidar Holen
43bb6a20ad Improve message for SC1052-54 about 'then;' 2017-07-08 17:25:54 -07:00
Vidar Holen
8f99d2b008 Don't warn about missing path for find -O3 . (#942) 2017-07-08 15:46:02 -07:00
Vidar Holen
79ae89076a Swap SC1041 and SC1042 for better sort order. 2017-07-08 15:21:58 -07:00
Vidar Holen
aa33280cb0 Improve here doc diagnosis 2017-07-08 14:00:02 -07:00
Vidar Holen
bd13224907 Use standard Haskell 'void' instead of custom 2017-07-08 10:23:51 -07:00
Vidar Holen
b064cf3038 Fix parsing here docs like << '#foo' (#947) 2017-07-07 22:26:12 -07:00
koalaman
79d6066450 Mention docker release tags in readme 2017-07-05 10:30:30 -07:00
Vidar Holen
1463cf773a Suggest explicit escape "\\n" for "\n" 2017-07-04 11:06:52 -07:00
Vidar Holen
31bb02d6b7 Ignore leading \ for commands (#927) 2017-07-03 16:40:11 -07:00
Vidar Holen
5bd33dbf92 Warn when piping/redirecting to mv/cp/echo/etc (#921) 2017-07-03 16:02:58 -07:00
Vidar Holen
a3c6aff0fb Improve parsing of line breaks in for statements (#926) 2017-07-03 13:58:10 -07:00
Vidar Holen
8184ef1e8b Don't complain about missing space in {( (#937) 2017-07-03 12:22:19 -07:00
Vidar Holen
a839a6657b Warn when commands start with dashes (#938) 2017-07-03 12:06:59 -07:00
Vidar Holen
a10b924570 Mention correct operator when warning about spaces around += (#944) 2017-07-03 10:44:09 -07:00
Vidar Holen
8f31ae913b Skip command argument when checking trap signal specs (#946) 2017-07-03 10:36:51 -07:00
Vidar Holen
a06ad41bfa Add Linux binaries to readme 2017-06-24 23:00:59 -07:00
Vidar Holen
21f5bf01eb Make TravisCI auto-build Linux executables. 2017-06-24 22:29:35 -07:00
koalaman
2ded4df6fa Merge pull request #935 from blueyed/README-fixes
README: style fixes, add Neomake
2017-06-14 10:47:28 -07:00
Daniel Hahler
90da31f226 README: style fixes, add Neomake 2017-06-13 21:22:50 +02:00
koalaman
b1486ec1e9 Merge pull request #903 from mrshu/mrshu/pushd-popd-like-cd
SC2164: Make SC2164 apply to `pushd` and `popd`
2017-06-12 09:54:05 -07:00
mr.Shu
954aa99b11 Analytics.hs: Refactor cd, popd and pushd checks
* Refactor the check of unchecked `cd`, `pushd` and `popd` into one
  function.

Signed-off-by: mr.Shu <mr@shu.io>
2017-06-12 12:16:01 +02:00
mr.Shu
79872f92f8 Merge branch 'master' of https://github.com/koalaman/shellcheck into mrshu/pushd-popd-like-cd
Signed-off-by: mr.Shu <mr@shu.io>
2017-06-12 11:29:19 +02:00
koalaman
bf9b841b07 Link to Windows executables in the Readme 2017-06-10 10:10:09 -07:00
Vidar Holen
5fad708df5 Zip compiled Windows executables. 2017-06-10 09:26:08 -07:00
Vidar Holen
5cece759cc Autobuild Windows .exe files 2017-06-09 21:40:59 -07:00
Vidar Holen
50c8172de4 Allow escaping ( with quotes in [ .. ] (#925) 2017-06-03 11:45:25 -07:00
Vidar Holen
ce950edbfd Don't trigger SC2026 when followed by empty literals (#923) 2017-06-03 09:38:47 -07:00
Royce Remer
f8e75d3e89 add compilation documentation for test runners 2017-05-28 16:06:55 -07:00
Vidar Holen
6f4e06d83c Avoid rescanning tree for lastpipe on every node. 2017-05-28 16:04:42 -07:00
Vladimir Panteleev
505ff7832f Recognize bash's shopt -s lastpipe
Fixes #732.
2017-05-28 14:56:49 -07:00
Vidar Holen
ac3f0b3360 SC2114 about rm -rf /usr is no longer silenced by -- 2017-05-28 14:44:58 -07:00
Vidar Holen
070a465b64 Recognize missing and superfluous cases in getopts loops. 2017-05-28 13:38:04 -07:00
Vidar Holen
4243c6a0bf Treat + like :+ to squash SC2068 2017-05-24 19:20:28 -07:00
Vidar Holen
8bc89bc451 Mention DevGuide in the README 2017-05-21 17:15:51 -07:00
Vidar Holen
5099ebf9b9 Allow comments after shellcheck directives. 2017-05-21 13:56:22 -07:00
Vidar Holen
d943ef6f77 Update Docker instructions. 2017-05-20 21:13:53 -07:00
mr.Shu
5e4c288cf4 SC2174: Do not warn at mkdir -pm 0700 ../foo
* Do not warn when `mkdir -pm 0700` is used with combination of paths
  like `..` and `.`

* Fixes #854

Signed-off-by: mr.Shu <mr@shu.io>
2017-05-16 11:45:04 -07:00
mr.Shu
9e35aa7ce8 SC2164: Make SC2164 apply to pushd and popd
* Since `pushd` and `popd` have the same failure cases, make the check
  for SC2164 apply to them as well.

* This commit also refactors the code a bit as `hasSetE` is now used in
  multiple places.

* Fixes #863.

Signed-off-by: mr.Shu <mr@shu.io>
2017-05-14 14:00:10 +02:00
Vincent van der Weele
21d7068bc8 Add VSCode integration to editor list 2017-05-09 19:03:26 -07:00
Vidar Holen
324aa3cc88 Improve and deduplicate string comparison warnings. 2017-04-22 21:09:42 -07:00
Dan Kegel
9c4f651e6b Document shell directive added by 944313c6 2017-04-18 09:57:38 -07:00
Vidar Holen
3cf8b9ceab Parse ksh nested arrays and warn about var=(( 2017-04-17 21:01:16 -07:00
Vidar Holen
5c01b6c7f5 Parse empty [ ] conditionals 2017-04-16 18:11:00 -07:00
Vidar Holen
7604e5eb58 Warn when using a glob as a command name. 2017-04-15 19:53:09 -07:00
Vidar Holen
4fb1080809 Warn when redirecting to a literal integer. 2017-04-15 17:20:33 -07:00
Vidar Holen
4f9a80db15 Remove leftover debug trace 2017-04-15 13:44:01 -07:00
Vidar Holen
3a38c50b8e Fix shellcheck warnings :P 2017-04-15 13:24:41 -07:00
Vidar Holen
fd79e80e78 Fix SC2120 triggering on sourced files and ${!var*} 2017-04-15 11:26:47 -07:00
Vidar Holen
1fd9b474ba Don't warn about quoting variables in [ -v 'bar[$foo]' ] 2017-04-15 10:57:10 -07:00
Vidar Holen
faafc99704 Don't trigger SC2037 when quoting (PAGER="cat" foo) 2017-04-15 10:33:56 -07:00
Vidar Holen
bc882fd85a Recognize more invalid shebangs 2017-04-08 16:34:00 -07:00
Vidar Holen
41b6e3d5eb Don't warn about [ -v foo ] being unassigned. 2017-04-08 15:19:47 -07:00
Vidar Holen
da1691912b Replace _otherwise with _ in cases 2017-04-08 14:00:52 -07:00
Vaibhav Sagar
0feb95b337 Implement fixes suggested by HLint 2017-04-08 11:07:32 -07:00
Vidar Holen
f0e0d9ffdb Don't suggest \[\] in PS1 for non-bash 2017-04-02 14:50:15 -07:00
Vidar Holen
3c75674b50 Warn about unquoted expansions in arrays. 2017-04-02 14:28:12 -07:00
Vidar Holen
8e5e77ad76 Don't suggest removing $ for (( $! + ${!var} )) 2017-04-02 09:49:47 -07:00
Vidar Holen
66c7cf19e2 Fix missing backslash in SC1003 about '\'' 2017-04-01 22:01:05 -07:00
xenopeek
36573b5b26 Update README.md
Command to install on Arch Linux based distros
2017-03-27 21:59:31 -07:00
Robert de Bock
9e4a9c8c6c Update README.md
Fixed a typo: scipts -> scripts.
2017-03-27 21:58:51 -07:00
Robert de Bock
c2fcb742db Update README.md
Adding a usage example for Docker.
2017-03-27 21:58:51 -07:00
Vaibhav Sagar
e8b4a79b65 Update resolver 2017-03-26 13:18:20 -07:00
Vidar Holen
08d1d37094 Stable version 0.4.6
This release is dedicated to Stardew Valley, for fixing the Harvest Moon
unplayable issue where Ann gives up on her inventions after marriage ;_;
2017-03-26 11:48:27 -07:00
Vidar Holen
e28e90133d Add missing import 2017-03-18 16:42:17 -07:00
Vidar Holen
2688a81526 Don't suggest indirection for 'declare var$n=foo' 2017-03-18 14:54:52 -07:00
Vidar Holen
82c3084438 Add HandBrakeCLI to list of stdin swallowing apps 2017-03-18 13:10:54 -07:00
Russ Kubik
c6ff1933b7 Update README.md 2017-03-17 09:32:53 -07:00
Vidar Holen
22c86256ac Decode UTF-8 sequences over 0x10FFFF as latin1 2017-03-10 10:11:05 -08:00
Daniel M. Capella
a3a4873190 readme: Add ALE Vim plugin 2017-03-08 10:10:24 -08:00
Vidar Holen
750212af39 Add less common actions to find -o check. 2017-03-03 20:43:00 -08:00
Vidar Holen
2154583fd3 Don't parse unicode quotes as real quotes. 2017-02-25 15:14:52 -08:00
Vidar Holen
35c74e4747 Getting command name from busybox now gets applet name 2017-02-12 10:56:29 -08:00
Vidar Holen
46fb91b44d Manually decode input files as lenient UTF-8. 2017-01-22 15:24:21 -08:00
Vidar Holen
128d5d6013 Don't warn about grep pattern issues when using -F. 2017-01-21 16:20:55 -08:00
koalaman
41176c23a6 Merge pull request #822 from bittorf/master
SC2164: show two possible variants for circumenting the warning
2017-01-15 15:58:19 -08:00
koalaman
342726f480 Merge pull request #823 from dasilvacontin/patch-1
Add TravisCI Setup to README.md
2017-01-15 15:57:09 -08:00
Vidar Holen
1863f2f12d Warn about += bashism in sh and dash. 2017-01-14 12:40:09 -08:00
Vidar Holen
8809a36952 Warn when finding HTML entities like &amp; 2017-01-14 11:59:31 -08:00
Vidar Holen
7f307c5775 Count | as a regex metacharacter for 2076. 2017-01-12 19:02:46 -08:00
David da Silva
eb12086d05 Fix typos in Travis CI section of the README.md 2017-01-11 11:48:57 +01:00
David da Silva
6259a32601 Add TravisCI Setup to README.md 2017-01-11 10:04:48 +01:00
Bastian Bittorf
4e13c7cbc1 SC2164: show two possible variants for circumenting the warning
always calling 'exit' is not good in e.g. functions.
the basic idea is at least that the returncode of
cd *is* evaluated somehow and not ignored.

Reported-by: Garance Alistair Drosehn <drosehn@rpi.edu>

Signed-off-by: Bastian Bittorf <bittorf@bluebottle.com>
2017-01-10 12:30:47 +01:00
Vidar Holen
edb01fa855 Warn about ( -d foo ) and similar. 2017-01-09 23:49:22 -08:00
koalaman
85e6c35845 Merge pull request #814 from Scorpiokat/master
This commit fixes #797
2017-01-03 21:25:45 -08:00
Ekaterina Efimova
43f667a8f9 Update Analytics.hs 2017-01-03 21:48:35 +03:00
Ekaterina Efimova
daacc98a8f Update Analytics.hs 2017-01-03 21:40:32 +03:00
Scorpiokat
40907b1636 This commit fixes #803 2017-01-03 14:55:12 +00:00
Scorpiokat
96168fc707 This commit fixes #797 2017-01-02 18:01:24 +00:00
Vidar Holen
6aee12a572 Warnings for braces/globs/arrays in [/[[. 2016-12-31 13:18:36 -08:00
Vidar Holen
0048f34b11 Merge branch 'master' of github.com:koalaman/shellcheck 2016-12-30 17:11:32 -08:00
Vidar Holen
e679ff222a Warn when using deprecated egrep/fgrep. 2016-12-30 16:55:31 -08:00
koalaman
6f5648faca Update README.md 2016-12-30 10:31:34 -08:00
Vidar Holen
30e94ea7ab Warn about comparisons and cases that can never match. 2016-12-29 14:04:49 -08:00
Vidar Holen
d8f8a2fa14 Minor 2% parser speedup 2016-12-29 10:56:00 -08:00
Vidar Holen
df3cc70658 Improve code for warning about escaped single quotes. 2016-12-28 21:51:28 -08:00
Vidar Holen
5669702362 Warn about missing and invalid subscripts in array assignments. 2016-12-28 18:58:03 -08:00
Vidar Holen
bd9d05c759 Warn about missing space in [ foo= bar ] 2016-12-27 21:20:59 -08:00
Austin English
af87fe9315 add missing references to dash 2016-12-20 17:10:55 -08:00
koalaman
c2850e436f Merge pull request #804 from austin987/readme2
README.md: sort package managers, add emerge (Gentoo)
2016-12-20 10:16:42 -08:00
Austin English
d73fc8f91d README.md: sort package managers, add emerge (Gentoo) 2016-12-20 12:11:10 -06:00
Vidar Holen
7124c113e8 Don't warn about .sh.version being unused (for Ksh) 2016-12-17 16:03:06 -08:00
Vidar Holen
f594f01d35 Add warnings about redirections without commands. 2016-12-17 15:03:52 -08:00
Vidar Holen
6ccb7e9129 Fix 'for file; do ..' counting $file as a safe variable. 2016-12-17 12:55:14 -08:00
Vidar Holen
838f0ce4dc Count "%(%Y%m%d)T" as a single format in printf. 2016-12-17 12:48:09 -08:00
Vidar Holen
105b09792c Fix SC095 about < /dev/null when using ssh -n 2016-12-17 12:41:00 -08:00
Vidar Holen
f6618d4332 Fix BSD style flag parsing to stop at -- 2016-12-11 10:58:01 -08:00
Vidar Holen
0a381be37b Improve heredoc delimiter handling. 2016-12-11 10:09:13 -08:00
Vidar Holen
46e47dad45 Don't quote source in 2041 and 2043. 2016-12-10 22:41:25 -08:00
Vidar Holen
fee6c94d40 Alias ash to dash with warning. 2016-12-10 10:57:01 -08:00
Vidar Holen
cf1c46d852 Add deprecation warning for tempfile 2016-12-10 09:58:27 -08:00
Vidar Holen
a40efffec9 Explicitly import Data.Monoid 2016-12-10 08:49:07 -08:00
Vidar Holen
44b96fca66 Merge branch 'bug562' 2016-12-03 10:21:49 -08:00
Vidar Holen
b4fb439191 Save string read by T_ParamSubSpecialChar 2016-12-03 10:19:14 -08:00
MortimerMcMire315
0897ab7092 Add handling for special characters in parameter substitutions.
Fixes koalaman/shellcheck#562. Special characters inside braces are
parsed into T_ParamSubSpecialChar instead of T_Literal so that they are
not flagged in the function checkInexplicablyUnquoted when sandwiched
between double quotes.
2016-11-28 16:06:02 -05:00
koalaman
9703f89f79 Merge pull request #774 from oyvindio/tag-releases-in-dockerhub
Push git tags to dockerhub as docker tags
2016-11-28 11:39:48 -08:00
koalaman
aadf02e635 Merge pull request #781 from austin987/patch-1
Add info/link on ignoring issues to README
2016-11-28 11:33:05 -08:00
Øyvind Ingebrigtsen Øvergaard
090051bdc1 Use $TRAVIS_TAG in $TAG if defined 2016-11-27 13:42:49 +01:00
Austin English
b8c96b4361 Add info/link on ignoring issues to README 2016-11-21 19:53:26 -06:00
Vidar Holen
f26038125d Allow spaces/comments before filewide annotations. 2016-11-20 18:06:36 -08:00
Vidar Holen
08f7ff37c5 Some cleanup and refactoring. 2016-11-12 15:51:36 -08:00
Øyvind Ingebrigtsen Øvergaard
60fc33ebdf Push git tags to dockerhub as docker tags 2016-11-11 20:32:05 +01:00
Vidar Holen
3a006f7bcb Use camelcase for cabal commands to align with stack. 2016-11-10 13:13:42 -08:00
koalaman
89b6fd58fa Reformat issue template 2016-10-31 18:20:39 -07:00
koalaman
069ddeffcc Merge pull request #766 from ryanoasis/issue-template
Add an issue template
2016-10-31 17:46:47 -07:00
Ryan L McIntyre
59c4ed106c Create ISSUE_TEMPLATE.md
* Suggestion for an issue template to help with the amount of issues
2016-10-31 20:25:55 -04:00
Vidar Holen
5efb724a3e Stable version 0.4.5
This release is dedicated to Google Inc for four great years of
employment and being good sports about hobby projects like this.
2016-10-21 14:00:50 -07:00
Vidar Holen
619b6c42f3 Improve parsing of fd close/duplicate redirections. 2016-10-21 11:31:58 -07:00
Vidar Holen
88c56ecd53 Allow unrecognized directives with warnings. 2016-10-14 12:14:20 -07:00
Vidar Holen
6b62b5bf7e Don't warn about [ a '>' b ] needing escapes. 2016-10-01 14:54:28 -07:00
Vidar Holen
8672af29ef Split duplicate SC1009 into SC1014 for if [ grep foo bar ] 2016-10-01 13:34:14 -07:00
Vidar Holen
1a8e34bfea Don't suggest grep -c when used with -o 2016-10-01 13:26:53 -07:00
Vidar Holen
b0dae063bf Add info when using 'find' without path 2016-09-25 11:56:32 -07:00
Vidar Holen
4fc4899803 Consider ${foo:=bar} an assignment. 2016-09-24 19:01:13 -07:00
Vidar Holen
cd4896192c Don't consider ~foo constant. 2016-09-24 15:32:44 -07:00
Vidar Holen
868d53af95 Warn about passing globs to unset. 2016-09-24 14:49:52 -07:00
Vidar Holen
6a4b86cbea Fix warning for >& 2016-09-24 14:08:00 -07:00
Vidar Holen
fe2398edc9 Warn about >& in sh 2016-09-24 14:03:54 -07:00
Vidar Holen
3a7dc86de1 Don't warn about unused vars with readonly -f 2016-09-24 13:42:20 -07:00
koalaman
1c0ec9c6f6 Merge pull request #734 from NLKNguyen/add_CI_CD_solution_with_Docker
Add CI/CD solution with Docker
2016-09-11 23:42:06 -07:00
NLKNguyen
84110dbef4 Change DOCKER_REPO value and add test runner 2016-09-08 23:57:46 -07:00
NLKNguyen
1a7e98beaf Use cleaner escaping method 2016-09-08 21:58:51 -07:00
NLKNguyen
a5d5831a2e Fix syntax error with traditional if-clause instead of escaping bracket 2016-09-08 21:41:06 -07:00
NLKNguyen
47201822f9 Change syntax style for readability 2016-09-08 21:31:23 -07:00
NLKNguyen
32689ef5eb Test Dockerfiles and Travis CI on downstream repos 2016-09-08 21:05:54 -07:00
Vidar Holen
87481dce25 Warn about printf hello world and printf "%s %s" foo 2016-09-06 21:16:59 -07:00
Vidar Holen
a90b6d14b3 Count b as a reference in ${a:b} 2016-09-05 14:01:53 -07:00
Vidar Holen
5a46eeb09a Allow #inline comments without SC2046. 2016-09-05 12:38:35 -07:00
Vidar Holen
47a7065a7a Add style note for 'mycmd; if [ $? -eq 0 ]'. 2016-08-28 20:54:08 -07:00
koalaman
dbafbb3b3b Merge pull request #722 from kpankonen/docker
add Dockerfile that will build shellcheck
2016-08-07 11:43:37 -07:00
Vidar Holen
13a2070a32 Support multidimensional KSH arrays and warn in Bash. 2016-08-06 18:40:08 -07:00
Kevin Pankonen
fa4874c044 add Dockerfile that will build shellcheck 2016-08-05 16:42:21 -07:00
Vidar Holen
6a71ff6f46 Don't suggest removing $ in (( ${COLUMNS-80} )) 2016-07-30 10:42:33 -07:00
Vidar Holen
36263fb3f5 s/range/class/ when warning about tr '[abc]' 2016-07-05 08:51:40 -07:00
Vidar Holen
6dc419bbf5 Improve warning for 'else if'. 2016-07-02 15:40:29 -07:00
Vidar Holen
7af3470a91 Improve parser errors when reparsing array indices. 2016-07-01 22:06:50 -07:00
Vidar Holen
42f7479fb8 Don't warn about missing shebang when using directives. 2016-07-01 22:02:06 -07:00
Vidar Holen
50084c06c5 Don't warn when $(seq) is used unquoted. 2016-07-01 21:26:46 -07:00
Vidar Holen
e3bef9dc97 Warn about (( 1 -lt 2 )) 2016-07-01 20:33:07 -07:00
Vidar Holen
6c1abb2dee Performance: make readDollarExpr fail early if no $ 2016-06-30 10:01:03 -07:00
Vidar Holen
43c26061b9 Improve parsing for ambiguous $((foo) ) and ((foo) ). 2016-06-26 22:13:48 -07:00
Vidar Holen
07fd5724b8 Recognize declare -A statements when value is inlined. 2016-06-26 14:57:52 -07:00
Vidar Holen
eb2472ada8 Merge branch 'master' of github.com:koalaman/shellcheck 2016-06-26 14:40:43 -07:00
Vidar Holen
3e5ecaa262 Parse indices of associative arrays properly 2016-06-26 14:39:49 -07:00
koalaman
e1cec6c5d3 Merge pull request #694 from eatnumber1/end_column
Emit the end line in the JSON
2016-06-18 15:09:58 -07:00
Russell Harmon
eaa319ec57 Emit the end line in the JSON.
This handles the case where the end line is not on the same line as the
start line when using the new end column feature.
2016-06-18 15:06:28 -07:00
koalaman
717b5e91f5 Merge pull request #693 from eatnumber1/end_column
Make SC1035 emit an end column
2016-06-18 15:05:44 -07:00
Russell Harmon
7f5f5b7fb5 Make SC1035 emit a proper end column
Example JSON output:
```
$ shellcheck -s bash -f json /dev/stdin <<< "[[0 -eq 1 ]]"
[{"file":"/tmp/zshNCNwPz","line":1,"column":1,"endColumn":3,"level":"error","code":1035,"message":"You need a space after the [[ and before the ]]."}]
```
2016-06-18 14:59:47 -07:00
Russell Harmon
856d57f7d8 PositionedComment and ParseNote contains end cols.
This change makes PositionedComment and ParseNote contain end columns.
It additionally modifies the JSON formatter to show the end column in an
"endColumn" property. No modifications to the messages shown by any
other formatter have been made.

Currently, all checks set the end column to the start column. It should
now be possible however to start setting the end column in the parser.
Additional work is needed to set the end column during AST analysis.
2016-06-18 14:58:00 -07:00
koalaman
c45e9d4878 Merge pull request #677 from Maffblaster/patch-1
Add Gentoo to supported distribution list.
2016-05-26 12:11:02 -07:00
Matthew Marchese
89c6f6c800 Add Gentoo to supported distribution list.
It was missing from the list. I thought it was best to add it. :)
2016-05-26 09:56:36 -07:00
Vidar Holen
85e69f86eb In (( x = y )), logic to not reference x also grabbed y 2016-05-24 09:12:47 -07:00
Vidar Holen
47fd16b8e8 Stable version 0.4.4
This release is dedicated to AlphaGo.
The second golden age of AI is upon us!
2016-05-15 13:53:37 -07:00
Vidar Holen
1d04754b37 Don't warn about a && b || c in if/while/until. 2016-05-14 17:14:32 -07:00
Vidar Holen
13ff0a7432 Warn when arrays are appended/assigned scalars. 2016-05-14 16:24:18 -07:00
Vidar Holen
40136fe249 Fix parsing of [[ a =~ {$var} ]] 2016-05-08 12:19:25 -07:00
Vidar Holen
86999ded1f Improve 'let' parsing, trigger unused var for ((a=1)) 2016-04-30 13:45:39 -07:00
Vidar Holen
7551a241ad Add missing warnings for {$i..10} similar to {1..$i} 2016-04-23 16:00:56 -07:00
Vidar Holen
2f0ae44de4 Fix parsing of here documents 2016-04-16 19:14:02 -07:00
Vidar Holen
51d8caf2c9 Add missing import 2016-04-16 09:53:15 -07:00
Vidar Holen
f835c2d4c1 Fix handling of spaces in shebangs. 2016-04-16 09:42:07 -07:00
Vidar Holen
db0c8c2dc9 Separate out command specific checks.
The checks use a better interface and give
an overall speed boost of 10%.
2016-04-10 17:01:40 -07:00
Vidar Holen
9911470d67 Don't warn about LINENO in dash 2016-04-09 09:56:07 -07:00
Vidar Holen
a5821c3a4d s/sh/bash/ in SC2176 because of posix guarantees. 2016-03-19 16:47:55 -07:00
Vidar Holen
c91083354f Warn about timing pipelines and compound commands in sh/dash. 2016-03-19 16:14:55 -07:00
Vidar Holen
2957fb64c9 Allow parsing 'time ( foo )' 2016-03-19 16:13:54 -07:00
koalaman
459e30804f Merge pull request #622 from Arguggi/master
Add stack support
2016-03-19 14:50:48 -07:00
koalaman
49569e10e6 Merge pull request #628 from benmwebb/patch-1
Fix a handful of typos.
2016-03-11 09:02:02 -08:00
Ben Webb
ba0221a1da Fix a handful of typos. 2016-03-10 21:27:07 -08:00
Vidar Holen
944313c6ba Directives after the shebang now apply to the entire script.
Also adds support for the shell= directive.
2016-03-08 20:16:16 -08:00
Vidar Holen
6af1aeb259 Add warning for multi-digit FDs in posix/dash. 2016-03-08 17:37:12 -08:00
Arguggi
b7c9d23452 Add stack support 2016-03-02 15:38:02 +01:00
koalaman
e792d69293 Merge pull request #608 from cs-shadow/master
Fix broken links in README
2016-02-17 09:25:56 -08:00
Chandan Singh
4d8f2eb707 Fix broken links in README
Presently, the links pointed to by "GCC error compatibility" and
"CheckStyle compatible XML output" are broken due to improper
way of referring files. This change fixes those links.

Also, this commit removes some trailing whitespaces in README.
2016-02-16 18:09:15 +00:00
Vidar Holen
8a3bd25f7c Improve error for missing final ) in $((foo) 2016-02-07 14:16:40 -08:00
Vidar Holen
825c1b5d22 Support parsing $((( as $( ((, with warning. 2016-02-06 22:19:29 -08:00
Vidar Holen
92473b512a Add warning for trailing spaces after \ breaks. 2016-02-01 20:20:34 -08:00
Vidar Holen
7e75d12ce1 Improve expansion in single quote false positives. 2016-01-26 19:57:18 -08:00
Vidar Holen
7d278c3ca1 Ignore SC2055 if rhs of either != is a glob. 2016-01-26 19:12:47 -08:00
Vidar Holen
5f1175fb58 Add special case warning to quote in eval echo {1..$n} 2016-01-25 18:46:55 -08:00
koalaman
257b794322 Merge pull request #578 from jwilk/master
Fix typo
2016-01-19 17:08:32 -08:00
Jakub Wilk
89572d3a96 Fix typo 2016-01-20 01:00:22 +01:00
koalaman
15edcbd4d5 Merge pull request #577 from neil-greenwood/readme-sed-quote
Fix missing quote in README.md
2016-01-18 09:00:53 -08:00
Neil Greenwood
736febaa3c Update README.md
Fix missing quote in `sed` example.
2016-01-18 14:53:15 +00:00
Vidar Holen
a21df2d88f Stable version 0.4.3
This is purely a bugfix bump that works on GHC 7.6.3,
as currently found in Debian stable and Ubuntu LTS.
2016-01-13 16:54:54 -08:00
Vidar Holen
d473fb8867 Use system over callCommand to allow linking on ghc 7.6.3. 2016-01-13 14:10:21 -08:00
Vidar Holen
f754363733 Add >= process-1.2.0.0 as dependency due to custom build. 2016-01-11 10:56:40 -08:00
Vidar Holen
ef1f8f535e Stable version 0.4.2
This release is dedicated to Tom Lehrer, who lives
the dream of having quit just to loaf about indefinitely.
2016-01-09 15:30:07 -08:00
Vidar Holen
f9909504dd Make SC2174 only trigger for nested directories. 2016-01-09 14:24:31 -08:00
koalaman
fa4cefda9d Merge pull request #572 from eatnumber1/mkdir
Add a warning when you mkdir with both -p and -m.
2016-01-09 13:58:53 -08:00
Russell Harmon
f2f6c66902 Add a warning when you mkdir with both -p and -m.
When using -p, parent directories will not be created with the mode
specified with -m and will instead be created using the default behavior
controlled by umask.
2016-01-08 14:15:11 -08:00
Vidar Holen
1f4dd85548 Change cabal Build-Type to Custom to actually use Setup.hs. 2016-01-05 14:10:45 -08:00
Vidar Holen
528381796e Allow escaped characters in [..] globs 2015-12-13 10:19:48 -08:00
Vidar Holen
ad7ad28246 Merge branch 'master' of github.com:koalaman/shellcheck 2015-12-12 15:53:18 -08:00
Vidar Holen
33ab998b02 Don't warn about quoting for [ -v var ] 2015-12-12 15:47:35 -08:00
koalaman
9c28237d52 Merge pull request #557 from eatnumber1/ignvars
Add more variables which are assumed to be set.
2015-12-10 20:26:00 -08:00
Russell Harmon
e0e5ba3a90 Add more variables which are assumed to be set.
This commit adds LC_MONETARY, LOGNAME, LD_LIBRARY_PATH, LANGUAGE,
DISPLAY, HOSTNAME, KRB5CCNAME, XAUTHORITY to be ignored when used
without initialization.
2015-12-10 20:05:50 -08:00
Vidar Holen
b4390414ef Fix remaining FIXME for tty error color output. 2015-12-06 12:48:53 -08:00
Vidar Holen
8acd5b13cd Add scripts for running shellcheck/tests interpreted. 2015-12-05 17:47:43 -08:00
Vidar Holen
d00ca0c283 Fix/generalize message for SC2070. 2015-12-05 17:29:06 -08:00
Vidar Holen
8bc98d89a7 Let SC2094 ignore echo/printf/sponge. 2015-12-05 16:50:11 -08:00
Vidar Holen
c7964a7a78 Warn about missing space in 'function foo{'. 2015-12-05 16:09:44 -08:00
Vidar Holen
8ec87d6655 Mention -- as alternative to ./* in SC2035 2015-12-05 13:45:56 -08:00
Vidar Holen
c3df2bf761 Don't warn about deprecated `` when just used for comments. 2015-12-05 13:33:39 -08:00
Vidar Holen
d1df3713ca Document --color in the man page. 2015-12-05 13:16:31 -08:00
Vidar Holen
23496e93b0 Fix compiler warning about missing field 2015-12-05 13:08:02 -08:00
koalaman
437e69fbba Merge pull request #553 from haguenau/add-color-switch
Add --color switch
2015-12-05 12:33:04 -08:00
David Haguenauer
63ad3f99ad Shorten long help line 2015-12-04 11:40:52 -05:00
David Haguenauer
0044c3dd6e Make use of --color with no argument equivalent to --color=always 2015-12-04 10:57:54 -05:00
David Haguenauer
a3d4101d6c Add initial support for --color 2015-12-03 17:55:56 -05:00
David Haguenauer
bd359c5c0f Delete trailing whitespace 2015-12-03 17:55:56 -05:00
Vidar Holen
498de63337 Mention that cabal installs to ~/.cabal/bin 2015-11-28 13:42:31 -08:00
Vidar Holen
52ab7dee2d Updating README.md to take over for shellcheck.net/about.html 2015-11-27 17:32:48 -08:00
Vidar Holen
1a5296659b Properly handle escaped double quotes in quoted backtick expressions. 2015-11-01 12:30:33 -08:00
Vidar Holen
a66ee2967c Trap warnings for kill/stop, non-XSI ints, "sig"-prefix and casing. 2015-10-31 17:36:24 -07:00
Vidar Holen
d985380f48 Consider "echo $(<file)" a bashism, and don't warn about UUOE. 2015-10-31 14:48:08 -07:00
Vidar Holen
6739c4a729 Count declare -p as a variable reference. 2015-10-31 14:16:45 -07:00
Vidar Holen
7415c9dcb7 Warn about non-posix function names like x-y 2015-10-31 13:53:17 -07:00
Vidar Holen
d3fc1f355d Merge branch 'master' of github.com:koalaman/shellcheck 2015-10-31 13:36:52 -07:00
Vidar Holen
48fd793581 Update getFlag function to also return non-flags. 2015-10-27 22:07:29 -07:00
koalaman
e5842e2e2b Merge pull request #516 from Fusl/patch-01
Fix typo "zyper" -> "zypper"
2015-10-22 13:59:50 -07:00
Fusl
cf445c7d20 Fix typo "zyper" -> "zypper" 2015-10-21 11:29:01 +02:00
Vidar Holen
ffb9578a98 Support parsing quoted test operators, and also warn about unicode dashes. 2015-10-17 16:33:21 -07:00
Vidar Holen
630f20e888 Count ~/ as dynamic for resolving source paths. 2015-10-17 10:50:07 -07:00
Vidar Holen
8f5f91f041 Warn about ]] with no corresponding [[. 2015-10-17 10:31:14 -07:00
Vidar Holen
8d9d4533c3 Don't trigger constant checks for -ot/-ef/-nt 2015-10-17 09:28:29 -07:00
koalaman
a4b4954a23 Merge pull request #512 from mimi1vx/opensuse-docu
install instructions for openSUSE
2015-10-17 09:10:12 -07:00
Ondřej Súkup
38cea9201d install instructions for openSUSE 2015-10-17 17:17:32 +02:00
Vidar Holen
4ce916ec1d Include bash builtin arrays in SC2128. 2015-10-14 12:31:09 -07:00
Vidar Holen
b9cb040128 Account for dereferencing for numerical ops in [[ ]]. 2015-10-14 11:11:17 -07:00
Vidar Holen
2488be7298 Don't warn about undefined HOSTNAME if it's being assigned. 2015-10-14 09:21:21 -07:00
Vidar Holen
d01b59a827 Don't warn about empty assignments when at end of command. 2015-10-13 12:16:39 -07:00
Vidar Holen
f77821625c Add dash as a first class supported shell. 2015-10-13 11:37:50 -07:00
Vidar Holen
1eece5b2ee Add warning about local in sh or not in bash functions. 2015-10-10 20:48:52 -07:00
Vidar Holen
58d45e3fa4 Warn about non-posix %q and flags for printf. 2015-10-10 20:14:17 -07:00
Vidar Holen
5aaa1a7d9a Split SC2165 messages into separate codes (2167). 2015-10-10 19:26:14 -07:00
Vidar Holen
3b36c2c820 Document exit codes in man page. 2015-10-10 19:19:38 -07:00
Vidar Holen
55692926b9 Don't consider {} and {a} brace expansions. 2015-10-03 21:12:28 -07:00
Vidar Holen
4172722167 Don't warn about quoted rhs of =~ when not a regex. 2015-10-03 15:21:57 -07:00
Vidar Holen
485593da2c Don't warn about disrespected quotes in ${#var}. 2015-10-01 18:56:45 -07:00
Vidar Holen
1181c6b3af Warn about ${!var} in POSIX mode. 2015-10-01 18:34:09 -07:00
Vidar Holen
ee181cfc43 Don't warn about comparisons when redirecting stderr for test. 2015-10-01 18:19:47 -07:00
Vidar Holen
c72667407b Merge branch 'master' of github.com:koalaman/shellcheck 2015-09-28 18:53:51 -07:00
Vidar Holen
5467a0f1d9 Account for set -o errexit and #!/bin/bash -e for unchecked cd. 2015-09-28 18:52:03 -07:00
Vidar Holen
3fc77d94ec Warn about [ -n foo ] when foo is entirely constant. 2015-09-28 18:46:32 -07:00
koalaman
23e0420cb1 Merge pull request #469 from spartacus06/fedora-readme
Add Fedora install procedure to README.md
2015-09-21 08:29:44 -07:00
Seth Jennings
a898165ac7 Add Fedora install procedure to README.md 2015-09-21 09:12:19 -05:00
Vidar Holen
ba5e3db31a Stable version 0.4.1
This is purely a bugfix bump because I botched the
0.4.0 cabal file and subsequent Hackage release :|
2015-09-05 19:32:37 -07:00
Vidar Holen
56145217fe Fixed the cabal file, which didn't include formatters :| 2015-09-05 19:17:22 -07:00
Vidar Holen
94d265ce41 Stable version 0.4.0
This release is dedicated to the Debian project,
for basically inventing the modern Linux distro.
2015-09-05 16:28:44 -07:00
Vidar Holen
0f00de80fd Support {n}>&1 named file descriptors. 2015-09-05 09:48:34 -07:00
Vidar Holen
c808c9b6fe End here doc tokens on < and >. 2015-09-03 20:58:21 -07:00
Vidar Holen
bf9297e2a5 Parse ksh ${ ..; } expansions. 2015-09-03 20:26:02 -07:00
Vidar Holen
7f547cc0ec Warn when using unescaped parens in eval. 2015-09-02 21:11:39 -07:00
Vidar Holen
01c27dc96a Parse double arithmetic negation, i.e. (( !!a )); 2015-09-02 19:31:22 -07:00
koalaman
856a204ec3 Merge pull request #446 from mbeniamino/master
Added FlexibleContexts extension in Parser.hs to fix compilation.
2015-08-23 10:01:22 -07:00
Matteo Beniamino
f054e2e2cc Added FlexibleContexts extension in Parser.hs to fix compilation. 2015-08-23 10:55:18 +02:00
Vidar Holen
090e09e4ca Support nested trinary expressions. 2015-08-22 14:20:20 -07:00
Vidar Holen
10276c878d Don't consider ${!os*} reference of 'os' 2015-08-22 13:55:17 -07:00
Vidar Holen
ae4aea4530 Adds support for a SHELLCHECK_OPTS environment variable. 2015-08-22 13:15:10 -07:00
Vidar Holen
d0029ae1d4 Ignore === in assignments, and add a special warning 1097 for ==. 2015-08-22 12:20:03 -07:00
Vidar Holen
eea7bc326e Improved parsing error expected messages. 2015-08-22 11:06:49 -07:00
Vidar Holen
73cd2cdd6f Also warn about missing 'then' before 'else' 2015-08-19 20:27:14 -07:00
Vidar Holen
a01862bc12 Adds a #shellcheck source=file directive to override source statements. 2015-08-19 19:09:55 -07:00
Vidar Holen
ccb6bf1ed5 Don't warn about uuoc for cat -n and similar. 2015-08-16 18:26:38 -07:00
Vidar Holen
136b654867 Update man page with info for -x. 2015-08-16 18:20:08 -07:00
Vidar Holen
f31c8bd3a3 Preliminary support for sourced files. 2015-08-16 17:18:51 -07:00
Vidar Holen
0dd61b65d8 Moved the various AST convenience functions to a separate module. 2015-08-16 12:53:23 -07:00
Vidar Holen
07747b30fb Warn about undefined behavior of test -a and -o. 2015-08-15 22:42:06 -07:00
Vidar Holen
26d16eb8ad Avoid new 2129 warnings when disabling the first one. 2015-08-15 14:23:45 -07:00
Vidar Holen
54b2d14847 Stop 2164 and 2103 about 'cd foo || exit' from overlapping. 2015-08-15 14:10:40 -07:00
Vidar Holen
f653362b18 Warn about bashism [^bar]. 2015-08-15 13:50:09 -07:00
Vidar Holen
f85441add9 Removed unused pragma. 2015-08-15 13:25:34 -07:00
Vidar Holen
67cfcfd206 Separated formatters into multiple files. 2015-08-15 12:51:13 -07:00
Vidar Holen
72eeafe002 Some cleanup to make room for future improvements. 2015-08-15 09:34:19 -07:00
Vidar Holen
6d9e8472e6 Less confusing message for SC2140 2015-08-02 19:55:47 -07:00
Vidar Holen
47d68019e5 Fixed exit status for missing files. 2015-08-02 19:13:01 -07:00
Vidar Holen
cbda90eeb5 Warn about zero-width spaces. 2015-07-25 13:59:00 -07:00
koalaman
722b0606e8 Merge pull request #416 from chadbrewbaker/master
cleanup
2015-07-23 12:26:59 -07:00
Chad Brewbaker
95cfd87589 cleanup 2015-07-23 12:51:38 -05:00
Vidar Holen
0a1beb883f Don't warn about unquoted :+ expansions. 2015-07-19 12:28:31 -07:00
Vidar Holen
83adcba88e Warn when nested loops have conflicting variable names. 2015-07-19 11:30:57 -07:00
Vidar Holen
35fb5073f4 Fixed cd foo; bar; cd -; check not trigger on top level 2015-07-18 19:58:09 -07:00
Vidar Holen
de59c3586b Warn about 'cd' when not used as part of a conditional 2015-07-18 19:37:58 -07:00
Vidar Holen
8894333556 Warn about 'export $foo' 2015-07-18 13:23:36 -07:00
Vidar Holen
b1843c520f Warn when using read without -r 2015-07-18 12:30:08 -07:00
Vidar Holen
d406ba9950 Special case messages for [ true ] and false/0/1 2015-07-18 11:47:28 -07:00
Vidar Holen
d5dfb4a7c1 Add a .ghci file to allow running ghci without cabal repl 2015-07-18 11:09:11 -07:00
Vidar Holen
7929a9dbba Makes literal check work for args to -z and -n 2015-07-18 11:08:42 -07:00
Vidar Holen
7e84ad031f Warn about [ foo ] when "foo" is non-constant with constant parts. 2015-07-18 09:56:58 -07:00
Vidar Holen
7eef12102b Make 2077 point to the = in [ foo=bar ] 2015-07-18 09:22:52 -07:00
Vidar Holen
0522a5f0bd Allow escaped linefeeds to break lines in $(()) 2015-07-15 09:01:29 -07:00
Vidar Holen
6c21e4671b Added bug reporting info to README.md. 2015-06-30 20:12:38 -07:00
Vidar Holen
3d83b87c9a Added copyright notice to individual source files. 2015-06-30 19:21:12 -07:00
Vidar Holen
f86d68bcc0 Fixed incorrectly documented flag syntax for -V. 2015-06-30 19:10:41 -07:00
Vidar Holen
1e65d36874 Included copyright information in the man page. 2015-06-30 19:07:08 -07:00
Vidar Holen
1ff67a61b4 Stable version 0.3.8. Now GPLv3!
This release is dedicated to Richard Stallman.
Happy hacking, and may we all live in a free GNUtopia!
2015-06-20 10:17:48 -07:00
Vidar Holen
349dfdab35 Relicense from AGPL v3 to GPL v3. 2015-06-20 09:52:07 -07:00
Vidar Holen
1ab29ddb39 Made SC2082 indirection message more sh friendly. 2015-06-14 17:20:52 -07:00
Vidar Holen
09b7788412 Don't consider declare -Ffp assignments. 2015-06-14 16:51:18 -07:00
Vidar Holen
ef2135f3aa Don't warn about unpassed parameters if used in child functions. 2015-06-14 16:14:05 -07:00
Vidar Holen
d10c3b2709 Don't warn about 2>&1 > foo if piping or capturing. 2015-06-14 15:39:44 -07:00
Vidar Holen
ca37794b7c Allow empty scripts, $()s and <()s. Also improves related error messages. 2015-06-14 14:30:11 -07:00
Vidar Holen
8b8b48ef55 Make quoted tilde message suggest $HOME instead. 2015-06-14 10:24:40 -07:00
Vidar Holen
aea0310a07 Added install instructions for native Windows 2015-06-14 10:16:32 -07:00
Vidar Holen
7fff088ce9 Don't output ansi escape codes on Windows 2015-06-07 18:08:23 -07:00
Vidar Holen
65ab8c8ecb Account for brace expansion in SC2115 (catastrophic rm). 2015-06-07 13:02:49 -07:00
Vidar Holen
3a041954d1 Don't warn about a&&b||c if c == printf 2015-05-24 12:41:54 -07:00
Vidar Holen
828378cdff Warn about injecting filenames into sh -c strings with find. 2015-05-23 13:03:07 -07:00
Vidar Holen
509cda4dcf Count mapfile/readarray as variable assignment 2015-05-10 13:13:42 -07:00
Vidar Holen
6076f0b1da Parse variables and subexpressions in brace expansions 2015-05-10 12:49:50 -07:00
Vidar Holen
1d26c280d6 Warn when failing to quote here strings. 2015-05-09 12:12:11 -07:00
Vidar Holen
c785d43e34 Fixed unquoted $@ warning message. 2015-05-09 12:07:33 -07:00
Vidar Holen
4c3e731445 Don't warn about a/b*c for ksh or when b == c 2015-05-09 11:48:08 -07:00
Vidar Holen
3940462da3 Warn about glob matching in [[ ]] for != as well as ==. 2015-05-09 11:34:34 -07:00
Vidar Holen
bb7ef5834b Warn on unindexed references for implicit arrays. 2015-04-21 19:19:15 -07:00
Vidar Holen
2f7bd556e8 Stable version 0.3.7
This is purely a bugfix bump that compiles on GHC 7.10
and uses a regex lib that doesn't crash on OS X.
2015-04-16 08:13:49 -07:00
Vidar Holen
081751c1b5 Fixed case sensitivity in 'trap' bashism test 2015-04-05 10:33:54 -07:00
Vidar Holen
cc86aab3f1 Added multiple new checks from checkbashisms 2015-04-05 10:25:00 -07:00
Vidar Holen
9f1f00cdd1 Switch from regex-compat to regex-tdfa 2015-04-04 16:26:28 -07:00
Vidar Holen
93debd3556 Add expect to list of known non-shells 2015-04-02 19:22:47 -07:00
Vidar Holen
47b971c582 Declared FlexibleContexts for GHC 7.10 2015-03-31 21:59:03 -07:00
Vidar Holen
f25ae90746 Stable version 0.3.6
This release is dedicated to Maxis: shaping the 90s
for yours truly with SimCity, SimCopter and El-Fish.
2015-03-28 12:27:39 -07:00
Vidar Holen
3daa47c0f2 Remove zsh specific variables. 2015-03-28 11:55:25 -07:00
Vidar Holen
ed56a837c3 Killed Zsh support 2015-03-20 10:03:56 -07:00
Vidar Holen
80cf5d9852 Include [] as glob chars to warn about quoting for 2015-03-19 18:29:47 -07:00
Vidar Holen
8e554ae3d4 Fix SC2143 to not warn about pgrep and other quasi-greps. 2015-03-12 08:31:49 -07:00
Vidar Holen
0a80188363 Fix parsing of ((a?b:c)) 2015-03-08 18:11:23 -07:00
Vidar Holen
0e1a64b6ba Warn about export/declare/local masking return values. 2015-03-08 14:17:43 -07:00
Vidar Holen
0a2cf208c8 Fixed quoted ~ warning to only trigger for ~/ 2015-03-07 23:48:01 -08:00
Vidar Holen
dcc10bbdf6 Fixed accidentally ignored undef warning for ${#foo} 2015-03-07 23:01:34 -08:00
Vidar Holen
2c2e41952f Improved missing shebang message. 2015-03-07 22:37:49 -08:00
Vidar Holen
0d74140650 Multiple wrong assignment warning fixes 2015-03-07 20:15:04 -08:00
Vidar Holen
955ad60823 Fixed parser errors not being excluded by -e 2015-03-01 13:44:57 -08:00
Vidar Holen
2573332d77 Fixed edge cases for braced reference extractor. 2015-03-01 13:44:18 -08:00
Vidar Holen
00c470f323 Improve SC2143 error message 2015-03-01 12:20:37 -08:00
Vidar Holen
63188282e9 Add warning for vars that are referenced but not assigned. 2015-02-28 18:43:22 -08:00
Vidar Holen
61b4b65184 Warn about obviously bad return values, like -1 or "foo" 2015-02-14 12:03:38 -08:00
Vidar Holen
39b2bf4378 Don't warn about modifying $@ or $IFS in a subshell 2015-02-14 10:43:49 -08:00
Vidar Holen
2fe117728d Count [[ -v foo ]] (and -R) as a variable reference 2015-02-13 20:10:18 -08:00
Vidar Holen
cde3ba8769 Add filename to JSON output. 2015-02-13 19:32:20 -08:00
Vidar Holen
33c78b7c95 Track variables created through coproc. 2015-01-27 10:11:17 -08:00
Vidar Holen
a485482979 Add support for coproc 2015-01-26 22:21:04 -08:00
Vidar Holen
895d83afc5 s/deprecated/legacy/ for backtick warnings. 2015-01-25 12:27:49 -08:00
Vidar Holen
39bc011757 Rewrote catastrophic rm detection, now simpler and more robust. 2015-01-25 12:18:06 -08:00
koalaman
fe0a398239 Merge pull request #295 from orlitzky/sdist-manpage
Add a pre-sdist hook to compile the man page (Github issue #247).
2015-01-24 13:10:09 -08:00
Michael Orlitzky
1be0f1ea75 Add a pre-sdist hook to compile the man page (Github issue #247).
This replaces the default preSDist hook in Setup.hs with our own. The
only thing the new hook does is compile the man page using callCommand
from System.Process.

If Pandoc fails, the entire sdist process will fail, since
Extra-Source-Files in the cabal file now lists the man page.

This is preferable to a build hook, because Pandoc pulls in a huge
number of dependencies. It's better to build the man page once and
ship it than to require every user to build and install pandoc before
he can build ShellCheck.

This creates another TODO item: an install hook can now be used to
install the man page along with the rest of ShellCheck. But beware,
the "man path" can vary from system to system.
2015-01-24 12:15:36 -05:00
Vidar Holen
c9aa133282 Fix pattern matching error in z=$(echo) 2015-01-02 18:06:10 -08:00
Vidar Holen
7b70500d41 Suppress SC2140 if the user just prefers quoting single items at a time. 2014-12-23 19:47:55 -08:00
Vidar Holen
8bed447411 Warn when trying to find -exec "shell command" \; 2014-11-22 12:16:30 -08:00
Vidar Holen
22710bf4d8 Fixed $! counting as a positional parameter reference. 2014-11-22 11:21:54 -08:00
Vidar Holen
a354685ab1 Warn about redirecting to globs in sh 2014-11-22 10:50:38 -08:00
Vidar Holen
a8ff7a02fd Fix $10 warning triggering for $?!, and also warn about $arr[index]. 2014-11-22 10:09:19 -08:00
Vidar Holen
c5479b8ca3 Stable version 0.3.5
This release is dedicated to Maru, internet celebrity cat.
Where would the web be without you? (Runner-up: Tim Berners-Lee)
2014-11-09 16:30:00 -08:00
Vidar Holen
d9dd58bec8 Warn about 'for $var in values'. 2014-11-09 16:22:01 -08:00
Vidar Holen
af1bb93aba Better warnings for repeated ;;s 2014-11-09 14:33:36 -08:00
Vidar Holen
e909c8ac42 More lenient line feed handling in test expressions. 2014-11-08 15:35:06 -08:00
koalaman
93140e31a0 Merge pull request #253 from vlajos/typofixes-vlajos-20141104
typo fixes - https://github.com/vlajos/misspell_fixer
2014-11-04 15:27:56 -08:00
Veres Lajos
97f3834852 typo fixes - https://github.com/vlajos/misspell_fixer 2014-11-04 21:55:42 +00:00
Vidar Holen
0369f43bac Fixed 2148 to not trigger if a shell is specified with -s. 2014-11-01 13:51:19 -07:00
Vidar Holen
eb2eae2888 Don't warn about ${args[@]} when nested in other ${} 2014-11-01 12:44:27 -07:00
Vidar Holen
30c0c1f27d Allow export "foo"="bar" in 2140 2014-11-01 12:20:10 -07:00
Vidar Holen
bff5d11566 Warn about `` in '' 2014-11-01 12:17:12 -07:00
Vidar Holen
eccb9f3f71 Added -or and -print0 to SC2146 2014-11-01 12:07:09 -07:00
Vidar Holen
2814572116 cat "$@" is not UUOC 2014-10-18 19:59:13 -07:00
Vidar Holen
90bafb9aba Fixed bug where (($b)) counted as a positional reference 2014-10-18 19:51:13 -07:00
Vidar Holen
39b88bbaac Removed Arch from readme, added Debian. 2014-10-12 17:13:35 -07:00
Vidar Holen
39805ab200 Don't warn about unpassed parameters in functions using 'set ..'. 2014-10-12 17:10:46 -07:00
Vidar Holen
9dadce96c0 Improve messages for missing 'then' statements. 2014-10-12 16:17:03 -07:00
Vidar Holen
1a0e208cc3 Consider find -exec when warning about vars in single quotes. 2014-10-12 14:00:17 -07:00
Vidar Holen
a69e27b774 Warn about swapped !# in the shebang. 2014-10-11 12:35:45 -07:00
Vidar Holen
b05c12223f Don't trigger SC2004 for (( $$ )) 2014-09-23 10:27:26 -07:00
Vidar Holen
38ead0385b Fixed quoting warnings for variables in $".." 2014-09-23 10:18:28 -07:00
Vidar Holen
9e8a11e57c Merge branch 'master' of github.com:koalaman/shellcheck 2014-09-23 10:12:23 -07:00
Vidar Holen
6b84b35ec0 Don't crash on empty files with -f gcc. 2014-09-23 10:11:15 -07:00
koalaman
669fdf8e5e Merge pull request #226 from aycanirican/patch-1
Update License in ShellCheck.cabal
2014-09-18 07:09:46 -07:00
Aycan iRiCAN
dccfb3c4a1 Update ShellCheck.cabal
Fixed License.
2014-09-18 09:10:07 +03:00
Vidar Holen
40ce949a56 Only warn once per unused variable name. 2014-09-07 12:55:08 -07:00
Vidar Holen
9f3802138f Prevent overlap of 2116 and 2005 in foo $(echo $(bar)) 2014-09-04 08:41:09 -07:00
Vidar Holen
2f3533fff6 Improve warnings for $ in (()). Also improves array subscripts. 2014-08-16 17:08:57 -07:00
Vidar Holen
f9c346cfd7 Ignore SC2033 when passing quoted function names. 2014-08-16 10:45:46 -07:00
Vidar Holen
5f7419ca37 Require a QuickCheck that doesn't break on UTF-8. 2014-08-10 17:16:27 -07:00
Vidar Holen
8494509150 Warn about missing shebangs. 2014-08-09 17:32:42 -07:00
Vidar Holen
8ba1f2fdf2 Better handling of directories and inaccessible files. 2014-08-08 09:36:17 -07:00
Vidar Holen
dbadca9f61 Check PS1/PROMPT_COMMAND/trap for simple variable references 2014-07-27 09:51:48 -07:00
Vidar Holen
0347ce1b7a Warn about quoted ~ in PATH 2014-07-26 13:14:28 -07:00
Vidar Holen
7fbe66e1c6 Warn about ineffectual quotes in a="/foo/'bar baz'"; $a 2014-07-26 12:15:54 -07:00
Vidar Holen
b000b05507 Parse empty and comment-only backtick expansions. 2014-07-26 12:07:59 -07:00
Vidar Holen
39423ddf81 Stable version 0.3.4
This release is dedicated to Kerbal Space Program,
which has delayed the project by at least a month.
2014-07-08 18:43:33 -07:00
Vidar Holen
875c2d2aad Removed Makefile from cabal file 2014-07-08 18:18:32 -07:00
Vidar Holen
64cc7c691a Warn about precedence in find -name -o -name -exec. 2014-06-22 14:16:24 -07:00
Vidar Holen
b9784cbcc0 Parse let arguments as arithmetic expressions. 2014-06-22 13:23:44 -07:00
Vidar Holen
1a3f6aadaf Support indices in array declarations 2014-06-22 10:35:45 -07:00
Vidar Holen
35756c2cd6 Delete outdated Makefile. 2014-06-22 09:16:54 -07:00
Vidar Holen
0fd351404f Allow escape sequences in here documents. 2014-06-16 14:18:29 -07:00
Vidar Holen
4caa7e7900 Removed accidentally submotted debug code 2014-06-10 00:49:43 -07:00
Vidar Holen
c11c0196d5 Fixed broken parsing of <( in arithmetics 2014-06-10 00:42:07 -07:00
Vidar Holen
b035331d4a Fixed failing test 2014-06-10 00:33:54 -07:00
Vidar Holen
d13253973b Updated readme 2014-06-07 23:25:01 -07:00
koalaman
d9c622ae33 Merge pull request #172 from jbnicolai/master
Adds homebrew installation steps to README.
2014-06-07 23:07:38 -07:00
Vidar Holen
aac7d76047 Don't warn when using find -print0 | xargs --null 2014-06-07 22:41:37 -07:00
Vidar Holen
fc421adb45 Reworked arithmetics to allow composite terms 2014-06-07 22:09:34 -07:00
Joshua Appelman
e0d3c6923a Removes trailing whitespace. 2014-06-08 01:42:32 +02:00
Joshua Appelman
9772ba9de4 Adds homebrew installation steps to README. 2014-06-08 01:42:20 +02:00
Vidar Holen
3a944de606 Warn when concatening strings and arrays. 2014-06-07 13:47:40 -07:00
Vidar Holen
3dd592a02a Support ;& and ;;& in case statements 2014-06-07 12:23:42 -07:00
koalaman
61531cbb10 Merge pull request #169 from Dridi/hackage
Add extra source files in the source tarball
2014-06-01 12:46:08 -07:00
Dridi Boukelmoune
d53087f056 Updated Extra-Source-Files accordingly with #165 2014-06-01 21:35:45 +02:00
Dridi Boukelmoune
39756b420e Add extra source files in the source tarball
This way ShellCheck can be entirely built (including the test suite)
from the Hackage tarball.

The source tarball can be generated using:

    cabal sdist
2014-06-01 17:59:24 +02:00
koalaman
52d4efc951 Merge pull request #168 from rodrigosetti/hlint
Collection of HLint fixes
2014-05-31 16:07:51 -07:00
Rodrigo Setti
5dac723593 Collection of HLint fixes
http://community.haskell.org/~ndm/hlint/
2014-05-31 22:20:49 +00:00
koalaman
2364fd58b6 Merge pull request #166 from rodrigosetti/better-gitignore
Using a more complete Haskell .gitignore
2014-05-31 10:42:17 -07:00
Vidar Holen
cde364c97b Updated README with new cabal instructions 2014-05-31 10:40:45 -07:00
Vidar Holen
98b790f87a Removed outdated version comment 2014-05-31 10:16:11 -07:00
Vidar Holen
726a4e5848 Merge branch 'cabal-version' of https://github.com/rodrigosetti/shellcheck into rodrigosetti-cabal-version
Conflicts:
	ShellCheck/Analytics.hs
	ShellCheck/Data.hs
2014-05-31 09:55:07 -07:00
Rodrigo Setti
0a9ed917e7 Test Suite in Cabal (cabal test)
Please run using "cabal test --show-details=streaming", there's a known
issue about this that was fixed in the latest version of cabal:
https://github.com/haskell/cabal/issues/1810
2014-05-31 01:30:23 +00:00
Vidar Holen
b10d31c8b7 Stable version 0.3.3
This release is dedicated to Jarkko Oikarinen, creator of IRC,
the fabric of the author's existence for so many years.
2014-05-29 21:01:34 -07:00
Vidar Holen
133c779701 Also check nested ifs for ssh/ffmpeg in read loops 2014-05-29 20:55:38 -07:00
Rodrigo Setti
b18ee3fdef Using a more complete Haskell .gitignore
Specially for using cabal sandbox.
2014-05-30 00:10:21 +00:00
Rodrigo Setti
3fcc6c44d8 Use version from generated cabal Paths module 2014-05-30 00:08:09 +00:00
Vidar Holen
d830a36bc8 Check for globs in test, e.g. [[ -e file* ]] 2014-05-25 12:04:18 -07:00
Vidar Holen
1af23fd131 Fix SC2051 to only warn about 1..$n and not 1,$n 2014-05-25 11:41:24 -07:00
Vidar Holen
d21b3362b2 Don't warn about splitting in select statements 2014-05-17 12:06:04 -07:00
Vidar Holen
6cd454e88b Suggest grep -q instead of [ "$(.. | grep)" ] 2014-05-17 10:56:36 -07:00
Vidar Holen
0b5f6b9762 Warn about aliases referencing $1/$*/$@ 2014-05-17 09:26:53 -07:00
Vidar Holen
3824e9cfc2 Fixed not recognizing --f=* as option in checkGrepRe 2014-05-15 09:14:57 -07:00
Vidar Holen
fdce0116da Fix parsing {} in regex 2014-05-13 19:20:34 -07:00
Vidar Holen
b069f7ed27 Added a shellcheck-static Makefile target 2014-05-11 13:58:56 -07:00
Vidar Holen
c4181d45d2 Warn about suspicious IFS, such as IFS="\n" 2014-05-10 15:37:02 -07:00
Vidar Holen
680f838c63 Warn about literal, unquoted {/} 2014-05-10 14:07:53 -07:00
Vidar Holen
e6d81ca7b7 Warn about using numerical test operators with strings 2014-05-10 12:37:02 -07:00
Vidar Holen
fd909eeca0 Fix parsing of &;; in case statements 2014-05-10 11:29:30 -07:00
Vidar Holen
deab146fab Don't warn about &&+|| when used with return 2014-05-09 18:08:55 -07:00
Vidar Holen
f9aeabc245 Improved error messages for SC2044/SC2045 2014-05-08 19:38:40 -07:00
Vidar Holen
558d8ffc6c Warn about suspiciously unquoted literal parts like "var="value"" 2014-05-07 21:47:27 -07:00
Vidar Holen
e96c4c3ffa Warn about aliases that expand at define time 2014-05-07 20:14:21 -07:00
Vidar Holen
c566efd442 Warn about UTF-8 BOMs in scripts. 2014-05-03 10:37:12 -07:00
Vidar Holen
47c220d59c Removed noisy SC1000 about unescaped $s 2014-05-03 10:19:01 -07:00
Vidar Holen
4bd902c5c4 Suggested updating cabal-install in the readme 2014-05-03 10:13:36 -07:00
Vidar Holen
033ce6d941 Allow zsh =(..) process substitution 2014-05-02 20:36:38 -07:00
Vidar Holen
6ad3f557fe Don't warn about sed '$s/foo/bar/' 2014-04-19 12:29:49 -07:00
Vidar Holen
d0bad6c057 Suggest grouping redirections when appending on 3+ lines 2014-04-19 11:53:54 -07:00
Vidar Holen
58c362f97c Warn about foo=(bar baz); echo $foo 2014-04-19 10:20:24 -07:00
Vidar Holen
5f568dd207 Merge branch 'master' of github.com:koalaman/shellcheck 2014-04-19 08:52:57 -07:00
Vidar Holen
2c1e414ac5 Only get vars after the last option in read 2014-04-19 08:50:47 -07:00
koalaman
6699109ab8 Merge pull request #139 from MichaelPereira/patch-1
Add pandoc to needed dependencies
2014-04-17 12:14:38 -07:00
Michael Pereira
423ca82296 Add pandoc to needed dependencies
The pandoc command is needed when compiling with make to run the tests
2014-04-17 15:08:37 -04:00
Vidar Holen
0a263579e0 Support for zsh short form for loops and anonymous functions 2014-04-13 13:37:37 -07:00
Vidar Holen
d63406abe4 Prevent SC2101 to collide with 2060 for tr -d [:space:] 2014-04-12 16:43:57 -07:00
Vidar Holen
81956d324d Don't warn when single quoting PROMPT_COMMAND and PS1 2014-04-05 17:08:03 -07:00
Vidar Holen
f549aad809 Suggest grep -c for grep|wc 2014-04-05 16:53:09 -07:00
Vidar Holen
f9f965693d Don't warn about single quoting $0 for xprop 2014-04-05 16:32:59 -07:00
Vidar Holen
727d940e10 Don't warn about expr when using <, > and friends 2014-04-05 16:29:35 -07:00
Vidar Holen
c26c2b8536 Stop using generic char 'c' in 2022 2014-04-05 16:17:52 -07:00
Vidar Holen
d8878ed852 Fixed warnings when assigning arrays to scalars 2014-04-05 14:56:12 -07:00
Vidar Holen
c3cc5f649f Fixed warning about \n in echo -n -e '\n' 2014-04-05 12:49:24 -07:00
koalaman
8bd4365cdb Merge pull request #122 from guywithnose/master
Add cabal update to install instructions
2014-04-05 11:40:46 -07:00
koalaman
a00a6fb53b Merge pull request #125 from inthecloud247/master
Instructions for adding ShellCheck to PATH
2014-04-01 17:59:48 -07:00
John Albietz
3332eba9a0 Instructions for adding ShellCheck to PATH 2014-04-01 14:26:03 -07:00
guywithnose
ad08bb64aa Add cabal update to install instructions
Before I ran `cabal update` I got this on `cabal install`

```
Config file path source is default config file.
Config file ~/.cabal/config not found.
Writing default configuration to ~/.cabal/config
Warning: The package list for 'hackage.haskell.org' does not exist. Run 'cabal
update' to download it.
Resolving dependencies...
cabal: Could not resolve dependencies:
trying: ShellCheck-0.3.2
```
2014-04-01 11:48:09 -04:00
Vidar Holen
f01e6e1a99 Check for accidentally overriding $PATH 2014-03-29 10:07:23 -07:00
Vidar Holen
de0145fb29 Stable version 0.3.2
This release is dedicated to knirch, mcandre, Dridi,
ptman, pihentagy, Riviera, and everyone else who keeps
submitting bug reports and feature suggestions!
2014-03-22 11:05:27 -07:00
Vidar Holen
0d4ae95e1d Recognize declare -x as exporting variables 2014-03-22 10:43:56 -07:00
Vidar Holen
50db49e2fb Rename Unquotable to QuoteFree 2014-03-22 10:27:59 -07:00
Vidar Holen
60aafae21d Count array indexes as references, even without $ 2014-03-22 10:22:34 -07:00
Vidar Holen
902cb9c303 Fixed up README 2014-03-19 09:57:01 -07:00
Vidar Holen
4f1fd43360 Don't suggest removing $ in (( 10#$n )) 2014-03-16 15:06:18 -07:00
Vidar Holen
ca5af5c55a Don't warn about decimals in (( )) for zsh/ksh 2014-03-16 14:56:23 -07:00
Vidar Holen
503cac3bb3 Merge branch 'master' of github.com:koalaman/shellcheck 2014-03-16 14:53:18 -07:00
Vidar Holen
2a9c9ae0ad Warn about using <=/>=, and don't warn about -gt 1.2 in ksh/zsh 2014-03-16 14:51:46 -07:00
koalaman
def4551991 Merge pull request #117 from mcandre/master
readme: markdown for link rendering
2014-03-15 16:17:07 -07:00
Vidar Holen
67f4a0d6eb Accept and warn about capitalization in keywords. 2014-03-15 16:08:33 -07:00
Andrew Pennebaker
f92f934688 readme: added compiler memory note 2014-03-15 16:49:05 -04:00
Andrew Pennebaker
d4059c30b7 readme: markdown for link rendering 2014-03-14 16:37:34 -04:00
Vidar Holen
b68de7f42b Don't warn about for s in "${!var}", it could be an array 2014-03-13 20:54:10 -07:00
Vidar Holen
7dacb62d36 Fixed determining shell for shebangs with flags 2014-03-09 17:24:05 -07:00
Vidar Holen
3423cde931 Check attempts to set variables with 'set' 2014-03-01 16:52:53 -08:00
Vidar Holen
b2d1aa01f7 Don't warn about commas when quoted in a=("a,b") 2014-03-01 15:30:51 -08:00
Vidar Holen
19e1bdf11f Warn about array assignments for /bin/sh 2014-03-01 15:16:31 -08:00
Vidar Holen
75d51087c8 Warn about functions using parameters that are never passed 2014-03-01 14:42:00 -08:00
Vidar Holen
ed524fb77f Don't warn about decimals when comparing with = 2014-03-01 10:24:22 -08:00
Vidar Holen
97045c4af1 Fixed x[0] not recognized as reference of x in arithmetics 2014-03-01 10:14:17 -08:00
Vidar Holen
1b806f6c9f Merge branch 'master' of github.com:koalaman/shellcheck 2014-03-01 10:06:03 -08:00
Vidar Holen
632c1614a1 Added support for |& 2014-03-01 10:05:43 -08:00
koalaman
00d9ef12e7 Merge pull request #105 from Dridi/dynamic_link
Dynamic linking to libShellCheck
2014-03-01 09:00:47 -08:00
Vidar Holen
d07294810b Allow \n before and after ||/&& in [[ ]] 2014-02-28 18:46:10 -08:00
Dridi Boukelmoune
948b750754 Make the executable depend on the library
It needed a bump to 1.8 for the minimum `Cabal-Version'. One downside is
that the executable also build-depends on the same libraries.
Alphabetical order is kept, except for the dependency to the ShellCheck
library itself.
2014-02-28 19:55:04 +01:00
Dridi Boukelmoune
41ae95116d Reformat ShellCheck.cabal for readability
Uses one line per `build-depends' or `exposed-modules'. Also got them
sorted by name. Folded `base' dependencies into a single one.
2014-02-28 19:44:09 +01:00
Vidar Holen
bf3c942294 Warn about using 'su foo' to continue as foo 2014-02-16 18:51:30 -08:00
Vidar Holen
055b40462d Improved $(echo ..) warnings 2014-02-16 13:26:50 -08:00
Vidar Holen
b087b7efb1 Some hlint fixes.
Ironically, this is the first time the linter has been linted.
2014-02-16 12:57:34 -08:00
Vidar Holen
5d8d57cf07 Suggest useless use of echo for $(echo $var) 2014-02-12 19:20:39 -08:00
Vidar Holen
661091a9da Added better message for SC1007, for 'var= value' 2014-02-12 18:26:41 -08:00
Vidar Holen
2ec60c2627 Added double prime to list of unicode quotes. 2014-02-08 14:15:04 -08:00
Vidar Holen
8b4909b238 Improve warnings for missing quotes. 2014-02-08 14:10:45 -08:00
Vidar Holen
95a3be6546 README: Updated URL, reformatted long lines 2014-02-08 09:58:11 -08:00
Vidar Holen
968e34e002 Parse forward ticks (acute accents) just like backticks and warn. 2014-02-08 09:50:20 -08:00
Vidar Holen
197b3e3f20 Some checks for accidental rm -r 2014-02-04 19:43:16 -08:00
Vidar Holen
0e464ea476 Stable version 0.3.1
This release is dedicated to the Flycheck team,
even though ShellCheck is written entirely in Vim.
2014-02-03 20:22:30 -08:00
Vidar Holen
811df6f0da Fixed cabal file 2014-02-03 20:21:26 -08:00
Vidar Holen
4e5d32b05a Added --version flag 2014-02-03 20:06:59 -08:00
Vidar Holen
c5141b77bf Fixed parser not accepting `` in arithmetic contex 2014-02-03 16:45:48 -08:00
Vidar Holen
9dfeb6b42a Added -s to the man page 2014-02-02 21:56:04 -08:00
Vidar Holen
77916d2645 Fixed compilation error on GHC7 2014-02-02 21:47:02 -08:00
Vidar Holen
4968e7d9ff Added -s flag to override dialect, e.g. -s ksh 2014-02-02 19:28:09 -08:00
Vidar Holen
075d58ee90 Replaced parser error for 'function' with shell-aware check. 2014-02-02 13:39:44 -08:00
Vidar Holen
6a4a5a815e Don't consider last stage of pipeline a subshell for Ksh/Zsh
Also fixes the problem where pipelines were considered a single subshell.
2014-02-02 13:03:26 -08:00
Vidar Holen
76a39f254b Refactoring, 25% speedup.
* Checks now use Writer monad instead of State

* Parser no longer emits notes unrelated to parsing.

* All checks are now passed a parameter value, containing shell type,
  map from notes to parents and such. This eliminates recalculation
  and removes the need for a special group of parent examining checks.
2014-02-02 04:59:17 -08:00
Vidar Holen
8ec9fa43fd Warn about break/continue in subshells and outside loops 2014-02-01 23:45:26 -08:00
Vidar Holen
e8634a3c27 Removed duplicate check for [[ a == b + 1 ]] 2014-02-01 20:45:44 -08:00
Vidar Holen
9ae776530b Check for [[ i + 1 = 2 ]] 2014-01-27 22:47:48 -08:00
Vidar Holen
0ec62390d5 Merge branch 'master' of github.com:koalaman/shellcheck 2014-01-27 22:13:04 -08:00
Vidar Holen
82328cd86e Warn about literal "\ " just like literal quotes.
Also, do it recursively.
2014-01-27 22:11:46 -08:00
koalaman
5b58da7249 Merge pull request #75 from michaelsanford/master
Added MacPorts cabal install information to README
2014-01-27 12:11:19 -08:00
michaelsanford
8676517270 Macports install info thanks to @myint
Capital P on MacPorts
2014-01-27 14:41:40 -05:00
Vidar Holen
4262c4b1bf Allow {} in arithmetic for loops 2014-01-26 12:44:51 -08:00
Vidar Holen
7ad0110443 Don't warn about sed '$d' or '$p' 2014-01-25 14:54:05 -08:00
Vidar Holen
e9bba2f75a Don't warn about comma separation in for f in {a,b} 2014-01-25 14:30:25 -08:00
Vidar Holen
74ea5eaeec Parse but warn about "else if" 2014-01-25 14:12:31 -08:00
koalaman
b7ee5f4410 Merge pull request #67 from michaelsanford/master
Added cabal setup instructions for Mac OS X to README
2014-01-24 21:15:10 -08:00
Michael Sanford
e294db171e Added Mac OS instructions with brew (relates #11)
Un-Markdown text
2014-01-24 15:59:10 -05:00
Vidar Holen
8c3d8d7cfa Stable version 0.3.0 2014-01-19 13:04:17 -08:00
Vidar Holen
380d6c3317 Cleaned up cabal file to make 'cabal check' pass. 2014-01-19 13:03:05 -08:00
Vidar Holen
16bd52333a man page: Added Directives section 2014-01-19 12:36:48 -08:00
Vidar Holen
cfb44b3fe2 Warn about 'cd $f; foo; cd ..' loop antipattern. 2014-01-17 09:02:14 -08:00
Vidar Holen
43ed5e748d Allow '# shellcheck disable=SC1234' to ignore by code. 2014-01-16 23:08:56 -08:00
Vidar Holen
4dca88aade Don't warn about quotes in variables for eval 2014-01-16 19:41:09 -08:00
Vidar Holen
1d2c7a8551 Warn about abused char classes, such as [10-15] and [:digit:] 2014-01-14 21:20:21 -08:00
koalaman
ba080e7e34 Merge pull request #61 from cheecheeo/master
expanded cabal file
2014-01-14 10:40:27 -08:00
John Chee
fc716738eb expanded cabal file 2014-01-13 19:14:18 -08:00
Vidar Holen
659709d529 Fixed ${!var} not counting as reference of var 2013-12-30 10:00:05 -08:00
Vidar Holen
5b4729d940 Parser: allow subshell function definitions 2013-12-30 09:50:14 -08:00
Vidar Holen
b936f28763 Merge branch 'manpage' 2013-12-15 19:43:02 -08:00
Vidar Holen
78d9a7ad97 Tweaked man page format 2013-12-15 19:40:05 -08:00
Vidar Holen
d540a98d33 Merge branch 'man_page' of https://github.com/Dridi/shellcheck into manpage 2013-12-15 18:44:49 -08:00
Vidar Holen
8c00850134 Minor performance tweaks (~10% improvement) 2013-12-15 18:43:34 -08:00
Vidar Holen
d1990e3396 Warn about 'i=i+1' and 'i=i + 1' 2013-12-15 16:11:17 -08:00
Dridi Boukelmoune
91fc4a046c Added a shellcheck(1) man page
The manual is mainly a copy/paste from the current documentation. It is
builded with pandoc, and written in markdown.

closes #50
2013-12-16 00:04:31 +01:00
Vidar Holen
95ebe1cd07 Fixed parser error for '..; done| ..' 2013-12-15 14:39:47 -08:00
Vidar Holen
27822a1f56 Warn about 'foo=bar echo $foo' 2013-12-14 16:06:19 -08:00
Vidar Holen
eb06b06475 Don't warn about single quoted vars for ssh 2013-12-14 15:28:58 -08:00
Vidar Holen
5d72432046 If printf string contains %, don't warn about using vars 2013-12-14 15:27:11 -08:00
Vidar Holen
da51b14789 Parser: accept here doc token strings more liberally 2013-12-14 15:20:15 -08:00
Vidar Holen
7be8485b8b Fixed parsing of 'time' in front of compound commands 2013-12-14 14:44:47 -08:00
Vidar Holen
a4d36ba0d2 Warn about while read f; do ssh "$f"; done 2013-11-29 23:05:41 -08:00
Vidar Holen
d4bc0f6e10 Don't require separator before do in 'for i do ..' 2013-11-29 16:22:37 -08:00
Vidar Holen
1011ae7b3c Fixed incorrect parsing of [ foo -a -f bar ] 2013-11-24 18:49:49 -08:00
Vidar Holen
d603ee1e89 Don't warn for A&&B||C if C is echo/exit/assignment 2013-11-24 16:15:10 -08:00
Vidar Holen
4fc518c877 Cleaned up command matching code 2013-11-24 15:48:07 -08:00
Vidar Holen
7fda86d6e2 Fixed warning for 'exec foo; exit 3' 2013-11-24 14:48:12 -08:00
Vidar Holen
6905373b6c Fix incorrect warning for 'foo > bar 2> bar' 2013-11-24 14:20:24 -08:00
Vidar Holen
1d8401d583 Assume variables have spaces by default 2013-11-17 16:16:58 -08:00
Vidar Holen
a89aee1a34 Assume variables have spaces/globs by default 2013-11-17 16:13:45 -08:00
Vidar Holen
4853dce3fe Fixed wrong quoting warning for foo=" "; foo 2013-11-17 15:00:07 -08:00
Vidar Holen
a793e09bab Added hint to suggest missing ;; in case 2013-11-17 14:41:55 -08:00
Vidar Holen
fbd85e93ee Added --exclude to filter out warnings 2013-11-17 13:41:42 -08:00
Vidar Holen
77f754fa32 Replace Prelude.catch with Control.Exception.catch 2013-11-15 17:31:55 -08:00
Vidar Holen
01d557abe6 More discriminating error codes 2013-11-14 22:46:09 -08:00
Vidar Holen
68cc00b6e8 Exit with 1 on comments and 2 on failure 2013-11-14 22:35:38 -08:00
Vidar Holen
8b7c0be06f gcc output mode now uses a tab width of 1 2013-11-14 22:23:55 -08:00
Vidar Holen
473bb666d8 Support for checkstyle compatible xml output 2013-11-13 22:39:35 -08:00
Vidar Holen
376d407ea1 Added gcc compatible output for editor integrations 2013-11-13 17:28:08 -08:00
Vidar Holen
2e13cedc4b Removed jsoncheck. Use 'shellcheck -f json -' instead 2013-11-12 21:39:41 -08:00
Vidar Holen
17515ad706 Added proper command line parsing 2013-11-12 21:22:52 -08:00
Vidar Holen
d8b5d6393a \" should not be treated specially in backticks 2013-11-12 18:27:18 -08:00
Vidar Holen
d404bc703d Show expose error code in shellcheck frontends 2013-11-10 12:22:33 -08:00
Vidar Holen
e5e08df1d9 Numbered messages 2013-11-10 10:55:46 -08:00
koalaman
1988cba147 Merge pull request #33 from daniellawrence/master
updated debian/ubuntu required packages
2013-11-07 10:21:48 -08:00
Daniel Lawrence
4cee7fd27f updated debian/ubuntu required packages 2013-11-04 16:00:47 +11:00
Vidar Holen
b75fe02aac Merge branch 'master' of github.com:koalaman/shellcheck 2013-11-03 13:58:33 -08:00
Vidar Holen
83c3dd3418 Accept ./? in function names 2013-11-03 13:58:06 -08:00
koalaman
020850dbbb Merge pull request #16 from carenas/master
gitignore and makefile for building with cabal and make
2013-11-03 13:51:13 -08:00
Vidar Holen
8d265aa25e Don't warn about expr if using : operator 2013-11-03 13:47:04 -08:00
Vidar Holen
c343217fd2 Added Fedora prerequisites in README 2013-11-03 13:27:10 -08:00
Vidar Holen
71bc26aefa Fixed parsing of | outside of groups in =~ regex 2013-11-03 13:13:24 -08:00
Vidar Holen
8a3d259ae6 Don't warn about single quotes in args to perl 2013-11-03 12:47:44 -08:00
Vidar Holen
3a9ae0ebf1 Accept dir-/basename due to edge cases like "/" and "foo" 2013-11-03 12:42:11 -08:00
Carlo Marcelo Arenas Belon
d6b903e6cc gitignore and makefile for building with cabal and make
makefile should also delete cabal generated files on cleanup so
they could be used interchangably.

ensure that all generated files are ignored as recommended by
bese practices.
2013-10-28 02:56:29 -07:00
Vidar Holen
b9f7f82e29 Stable version 0.2.0 2013-10-27 16:04:33 -07:00
Vidar Holen
6d0bfcf37a Fixed parser accepting spaces after here doc token 2013-10-27 16:02:27 -07:00
Vidar Holen
e0bbb89d00 Fixed parser bug where }> wasn't recognized as Rbrace 2013-10-27 15:36:47 -07:00
Vidar Holen
a0a58d432a Merge branch 'master' of github.com:koalaman/shellcheck 2013-10-20 15:04:45 -07:00
Vidar Holen
206900fb64 Use exit status and stderr properly in terminal tool 2013-10-20 15:03:14 -07:00
koalaman
794a5523d1 Merge pull request #12 from mcandre/master
README: clarify build step
2013-10-20 13:47:15 -07:00
Andrew Pennebaker
389c7b670c README: clarify build step
Help those unfamiliar with cabal to install shellcheck.
2013-10-20 16:33:00 -04:00
Vidar Holen
b1af7bb8f2 Fixed parser error for 'for ((;;)) ; do' 2013-10-11 20:03:55 -07:00
Vidar Holen
157fea73da Suggest ./* instead of * for command arguments 2013-10-06 15:54:31 -07:00
Vidar Holen
b439f02b8e Improved assignment parsing: track indices and += vs = 2013-10-06 14:44:43 -07:00
Vidar Holen
710a28c572 Revert "Fixed parsing for 'eval var=(values)'", because it fails for 'eval $x=foo'
This reverts commit 34e69556b1.
2013-09-29 21:35:20 -07:00
Vidar Holen
702d57b655 Warn about unicode quotes 2013-09-29 21:22:42 -07:00
Vidar Holen
34e69556b1 Fixed parsing for 'eval var=(values)' 2013-09-29 21:00:29 -07:00
Vidar Holen
7c411b39ac Fixed warnings for read -p "Name: " 2013-09-29 20:55:26 -07:00
Vidar Holen
5a959bc340 Fix parser errors for unclosed $( in here docs 2013-09-21 16:27:17 -07:00
Vidar Holen
fb5f72951d Don't warn about unused variables for read '' 2013-09-12 19:11:42 -07:00
Vidar Holen
7630136d6c Move command and variable lists to ShellCheck.Data. 2013-09-12 18:50:33 -07:00
Vidar Holen
dacb8c597f Fixed a series of extglob parsing oddities and edge cases 2013-09-04 13:02:30 -07:00
Vidar Holen
d99aaaf8dc Merge branch 'master' of github.com:koalaman/shellcheck 2013-09-03 14:09:50 -07:00
Vidar Holen
876831b419 Fixed up readme 2013-09-03 14:08:30 -07:00
Vidar Holen
24580609b8 Merge branch 'master' of https://github.com/carenas/shellcheck into carenas-master 2013-09-03 14:06:38 -07:00
koalaman
5828abe324 Merge pull request #7 from carenas/master
Include jsoncheck in 'make clean' target and update required ubuntu package list.
2013-09-03 14:04:49 -07:00
Carlo Marcelo Arenas Belon
c229d3929a build: update recommended Ubuntu package list
last still supported version to use ghc6 was lucid, so it is
better to refer instead to ghc 7 as used since precise
2013-09-01 21:46:32 -07:00
Carlo Marcelo Arenas Belon
31907ca51d build: include all binaries for clean 2013-09-01 21:37:30 -07:00
Vidar Holen
58b8e0ab70 Suggest pgrep when grepping ps 2013-08-31 18:32:07 -07:00
Vidar Holen
9586a46c9c Warn about assigned but unreferenced variables 2013-08-31 18:26:20 -07:00
Vidar Holen
bb49cf8e65 Parse the contents of unquoted here documents 2013-08-31 17:03:15 -07:00
Vidar Holen
de1fa61560 Warn about client side expansion in ssh strings/heredocs. 2013-08-03 21:19:32 -07:00
Vidar Holen
07b1fd6f44 Allow :+- in function names. :(){ :|:;};:, anyone? 2013-08-03 20:22:32 -07:00
Vidar Holen
d0caa1e1df Don't warn for 'find .. | xargs -0' or 'ls -N | ..' 2013-07-25 19:58:53 -07:00
Vidar Holen
4f7926cf26 Stable version 0.1.0. 2013-07-24 00:23:23 -07:00
Vidar Holen
62566ee016 Clarified warning for expr 2013-07-24 00:17:31 -07:00
Vidar Holen
c1731bd72c Don't warn about redirecting sudo to /dev/null 2013-07-23 23:46:40 -07:00
Vidar Holen
4d9f8ebb39 Allow lack of spaces/separators in for((;;))do .. 2013-07-23 23:30:48 -07:00
Vidar Holen
6aab109afb Fixed up some warning messages. 2013-07-23 23:13:28 -07:00
Vidar Holen
8c5f0a062e Warn about suspicious quotes in "foo "$var" bar" 2013-07-23 22:48:35 -07:00
Vidar Holen
5ba382d79b Fixed parsing of IFS= read as single assignment 2013-07-23 22:12:13 -07:00
Vidar Holen
d28f1fff56 Tried to make [ foo=bar ] messages simpler 2013-07-23 21:53:01 -07:00
Vidar Holen
1784972af7 Don't warn about echo "--------" is posix mode 2013-07-23 21:40:55 -07:00
Vidar Holen
6974497f45 Don't warn for \. (regex) and \, (printf "%q" output) 2013-07-23 21:35:00 -07:00
Vidar Holen
b147419717 Don't warn for $ on $(( ${array[refs]} )) 2013-07-23 21:29:19 -07:00
Vidar Holen
d6dab3bd05 Don't warn about IFS= read .. 2013-07-23 21:23:33 -07:00
Vidar Holen
cd1368b434 Added $PWD as a variable likely to contain spaces 2013-07-23 21:03:43 -07:00
Vidar Holen
f348661e7e Generalized for f in $(ls) warning, due to many edge cases. 2013-07-23 20:54:04 -07:00
Vidar Holen
9393e4405b Fixed accidental warning for $".." 2013-07-11 09:32:13 -07:00
Vidar Holen
e84d5abc3e Support for recursive regex groups 2013-07-10 23:47:25 -07:00
Vidar Holen
0a2314cdcd Also allow array syntax for args to readonly. 2013-07-10 23:15:08 -07:00
Vidar Holen
3e39411b38 Don't suggest ${foo//bar/baz} for #!/bin/sh 2013-07-10 23:14:10 -07:00
Vidar Holen
2214889a36 Improved messages for missing spaces in [..] 2013-07-10 23:03:42 -07:00
Vidar Holen
5a3493740e Warn for [ \( foo = bar\) ] 2013-07-10 18:05:51 -07:00
Vidar Holen
e6f2ee1f88 Don't try to parse $'..' in "" 2013-07-10 17:41:38 -07:00
Vidar Holen
3832ca9d5c Simplified PS1 checks. 2013-07-09 23:43:27 -07:00
Vidar Holen
636c6a9336 Parser support for export a=(b c). Also declare/local/typeset. 2013-07-09 23:32:13 -07:00
Vidar Holen
6b9cad55a5 Better unquoted message, seeing as how it's so common. 2013-07-09 22:18:22 -07:00
Vidar Holen
4780da31c2 Added bashism warning for &> 2013-07-09 22:11:17 -07:00
Vidar Holen
d04262c70f Fixed broken recursive backtick expansion. 2013-07-09 21:53:15 -07:00
Vidar Holen
8055b6f9c5 Fixed warning for trap '$VAR' 2013-07-09 09:26:48 -07:00
Vidar Holen
c3211e559d Added check for for f in $(find ..) similar to $(ls) 2013-07-08 21:09:27 -07:00
Vidar Holen
3d47609e78 Warn for [ $foo = *glob* ] 2013-07-08 20:45:15 -07:00
Vidar Holen
52f2f71b40 Added missing id/recursing defintions for DollarBracket 2013-07-08 09:51:57 -07:00
Vidar Holen
599beff5b1 Moved shebang verification to parser 2013-07-08 09:39:54 -07:00
Vidar Holen
a08e60cd07 Don't try to parse scripts declared as perl, ruby or python 2013-07-07 13:22:29 -07:00
Vidar Holen
2500b2cce6 Fixed parser warning for \{foo,bar\} 2013-07-06 15:36:06 -07:00
Vidar Holen
56e0119db1 Fixed some incorrect warnings for PS1 escapes. 2013-07-05 19:12:13 -07:00
Vidar Holen
76c5af2973 Parser support for $[..], plus deprecation warning. 2013-07-05 09:42:08 -07:00
Vidar Holen
fc4a6043d7 Reformatted ugly AST definition 2013-07-05 09:24:22 -07:00
Vidar Holen
a20a3499ed Improved bad indirection detection 2013-07-05 09:15:08 -07:00
Vidar Holen
73c6202842 Fixed misplaced uuoc for 'cat foo' outside pipe. 2013-07-04 14:27:03 -07:00
Vidar Holen
10b5e44ad0 Improved help for missing here doc terminator. 2013-07-04 14:19:54 -07:00
Vidar Holen
66cebe7c7b Don't warn about quoting when $var is the command name. 2013-07-04 13:49:00 -07:00
Vidar Holen
af4d24c6f6 Check for 'echo "\n"'. 2013-07-04 13:42:31 -07:00
Vidar Holen
fc3045232f Don't warn about f=/dev/null in 'foo $f > $f' 2013-07-04 13:18:46 -07:00
Vidar Holen
dbd4ff109c Mention second level structure being parsed when error. 2013-07-04 13:07:27 -07:00
Vidar Holen
d2c5802a9d Fixed UUOC warning for 'cat * | ..'. 2013-07-04 12:26:59 -07:00
Vidar Holen
ab20747ef2 Removed warning for ~ in the middle of strings. Too common. 2013-07-04 12:01:34 -07:00
Vidar Holen
9e84ff66f7 Warn about $() but not quotes in 'if $(cmd); ..' 2013-07-04 11:44:36 -07:00
Vidar Holen
b060370b92 Added and improved parse warnings for missing spaces. 2013-07-03 16:37:58 -07:00
Vidar Holen
f557ac3324 Added check for 'exec foo; cmd' 2013-07-02 22:37:33 -07:00
Vidar Holen
5d46c8a53f Added check for functions used with sudo/xargs/etc 2013-07-02 21:35:17 -07:00
Vidar Holen
99be2736a1 Doubled speed by applying all checks in one iteration. 2013-07-02 20:29:07 -07:00
Vidar Holen
6aafc86a67 Added check for './ file'. Apparently people do that. 2013-07-02 20:09:01 -07:00
Vidar Holen
9cfa25cb56 Added check for ~ in quotes 2013-07-02 19:52:09 -07:00
Vidar Holen
499f7c8733 Warn for possible bad quote nesting like 'echo 'foo'' 2013-07-01 10:01:58 -07:00
Vidar Holen
651bab73de Fixed crash for ''foo due to unsafe 'last' 2013-07-01 09:14:33 -07:00
Vidar Holen
652f8a24fa Added most checks from 'checkbashisms'. Thanks to Braakman, Rodin and Gilbey! 2013-06-30 12:13:18 -07:00
Vidar Holen
f820298b6e Added recursive parsing support for .. 2013-06-26 21:04:39 -07:00
Vidar Holen
25ee7e20f4 Added awkward check for PS1 escapes outside \[..\] 2013-06-25 20:59:54 -07:00
Vidar Holen
438c4ec572 Fixed up warnings for \r, and added warnings for &nbsp; 2013-06-21 01:22:11 -07:00
Vidar Holen
5794f3d390 Fixed parsing of "test$" 2013-06-21 00:33:20 -07:00
Vidar Holen
092073d0b3 Fixed parsing for case foo \n in .. 2013-06-20 23:57:08 -07:00
Vidar Holen
51cd951baa Added warnings for sudo cmd > file 2013-06-18 20:08:56 -07:00
Vidar Holen
3b246f94a3 Fixed parsing for cmd &> file 2013-06-18 20:08:33 -07:00
Vidar Holen
f3c8ce3e3d Initial Cabal file 2013-06-18 09:29:39 -07:00
Vidar Holen
564e3c5413 Don't start comments for #s in the middle of words. Thanks Mitch! 2013-06-07 18:32:59 -07:00
Vidar Holen
103b037921 Fixed parsing for [] in =~ regex 2013-05-31 14:22:13 -07:00
Vidar Holen
1b8b3b84d0 Fixed broken test for for f in "*.mp3"; do .. 2013-05-29 21:05:15 -07:00
Vidar Holen
1dbbc51f86 Improved regex parsing. To think [[ f =~ f( ]] )* ]] is valid.. 2013-05-28 21:32:15 -07:00
Vidar Holen
6b89f33d0c Warn about arg='--foo="bar"'; cmd $arg 2013-05-28 20:06:20 -07:00
Vidar Holen
b279411d70 Rewrote variable tracking code for future expansion 2013-05-27 20:54:03 -07:00
Vidar Holen
fc1af1b918 Also check for overridden time parameters for /bin/sh 2013-05-25 22:43:17 -07:00
Vidar Holen
17cf796486 Different checks per shell, and increased bashism detection. 2013-05-25 22:33:21 -07:00
Vidar Holen
cf67bf2294 Added check for 'time --format' and such, which Bash swallows. 2013-05-23 22:28:12 -07:00
Vidar Holen
e8a0fe09bf Added error for ${foo$n} 2013-05-23 21:47:25 -07:00
Vidar Holen
7ae5351de3 Added warning for foo$n=42 2013-05-23 21:31:29 -07:00
Vidar Holen
034cfee66e Fixed glob parsing for [[:class:]] and [~.:]. Thanks to dualbus! 2013-05-23 20:44:28 -07:00
Vidar Holen
13d4ea6540 Don't complaing about lack of quotes for 'local' and 'declare' 2013-05-20 11:58:08 -07:00
Vidar Holen
92d0ae8b6b Allow [ foo \> bar ], while warning for [[ .. \> .. ]] and [ 1 \< 2 ] 2013-05-14 15:59:58 -07:00
Vidar Holen
10d4abf235 Warn for test n > 4 2013-05-14 15:23:28 -07:00
Vidar Holen
ce0b313b93 Better messages for ignored backslashes like 'echo foo\n' 2013-05-13 09:15:45 -07:00
Vidar Holen
2f21ced552 Warn for subshell modifications using 'let' 2013-05-02 12:38:47 -07:00
Vidar Holen
82b16b4076 Warn for [[ $foo > 3.14 ]] 2013-03-22 17:10:30 -07:00
Vidar Holen
6abb5fe72b Quick hack to read and discard array indexing in arithmetic contexts 2013-03-22 16:42:40 -07:00
Vidar Holen
9f244edae3 Warn on "grep foo*.jpg" and "grep *foo*" 2013-03-01 17:28:41 -08:00
Vidar Holen
d2e2d06978 Add check for [[ "foo" ]] 2013-02-14 19:43:43 -08:00
Vidar Holen
585529a636 Return list of notes rather than a Map -> Map 2013-02-11 19:26:40 -08:00
Vidar Holen
05cb806642 Also warn for '$((foo)) $(cmd) ${foo}', not just '$foo' 2013-02-07 17:53:47 -08:00
Vidar Holen
795af72cf7 Fixed warning for ${#@} 2013-02-06 22:35:24 -08:00
Vidar Holen
899d9eb445 Warn against open parenthesis in normal words 2013-02-05 20:35:39 -08:00
Vidar Holen
84f87002b7 Split up numerical and legal binary op function 2013-02-05 20:15:13 -08:00
Vidar Holen
e64698dc78 Improved empty then/elif/else clause errors 2013-01-26 17:21:34 -08:00
Vidar Holen
dd115a6d35 Warn on trap "echo $num" USR1 2013-01-25 20:32:25 -08:00
Vidar Holen
f6f05234bf Warn on for f in 1,2,3 and for f in ls; 2013-01-25 20:15:42 -08:00
Vidar Holen
0d3dded238 Check if =~ is applied to something that looks like a glob 2013-01-25 20:06:18 -08:00
Vidar Holen
02efc2e945 The test cases are fun, but not up to date. The unit tests are better. 2013-01-23 17:18:18 -08:00
Vidar Holen
0c66cfb936 Add warnings for empty then clauses 2013-01-23 17:15:55 -08:00
Vidar Holen
844a07afa0 Added warning for empty do clauses 2013-01-23 17:12:05 -08:00
Vidar Holen
389d5588d8 Make [[ foo=bar ]] check say 'operator' instead of '=', because != 2013-01-22 14:50:30 -08:00
Vidar Holen
7c18ecee4f Parse single/double quoted literals in arithmetic context 2013-01-14 21:52:09 -08:00
Vidar Holen
b517ad9e19 select loops and bases in arithmetic contexts 2012-12-31 18:48:57 -08:00
Vidar Holen
059ef63b44 Don't warn for awk '$1' 2012-12-12 18:27:57 -08:00
Vidar Holen
1d7c6f68b4 Fixed bad for f in $(ls *.mp3) after T_Glob 2012-12-06 23:43:19 -08:00
Vidar Holen
bb6c155341 {1..$n} is only a problem in Bash 2012-12-05 09:53:16 -08:00
Vidar Holen
6d2e739e09 Hacked in place warnings for if [[ 1 ]] then :; fi 2012-12-02 23:47:17 -08:00
Vidar Holen
6e263e6b76 Parsing support for array indices in assignments. 2012-12-02 21:29:03 -08:00
Vidar Holen
b765ed1a44 Removed superfluous messages for [ cow] 2012-12-02 20:40:01 -08:00
Vidar Holen
1fb3380e68 Added warning for find . -execdir rm *.jpg \; 2012-12-02 18:10:00 -08:00
Vidar Holen
6402f7f4a3 Fixed space warning for foo=$(echo $foo) 2012-12-02 17:19:44 -08:00
Vidar Holen
d3a4c9852f Read any -* as binary/unary op, and warn on unknown. 2012-12-02 14:50:31 -08:00
Vidar Holen
35b8d58c3e Fixed warning for [[ greplol ]] 2012-12-02 14:15:50 -08:00
Vidar Holen
55a4c3c44f Added check for bashisms with #!/bin/sh 2012-12-02 14:08:50 -08:00
Vidar Holen
1a4301ea98 Added check for "#!/usr/bin/env bash -x" 2012-12-02 12:40:46 -08:00
Vidar Holen
3c2d9557e0 Parse the shebang separately 2012-12-02 12:02:29 -08:00
Vidar Holen
8c1ab0c9b6 Fixed warning for tr abc '[d*]' 2012-12-01 13:19:40 -08:00
Vidar Holen
b144700ae0 Support for arithmetic for loops. 2012-12-01 12:56:35 -08:00
Vidar Holen
ff85c67c29 Fixed mistaked message for tr '[:upper:]' 2012-11-30 16:13:42 -08:00
Vidar Holen
a73d898bd8 Added warning for { if :; then :; fi > cow } 2012-11-30 15:16:20 -08:00
Vidar Holen
34259f16db Fixed message for (($1)) 2012-11-30 14:32:20 -08:00
Vidar Holen
24f91ae711 Revert "Added warning for fi }, and not for ) }"
This reverts commit ea4176691d.

I must have had some crack for breakfast.
2012-11-30 10:24:35 -08:00
Vidar Holen
ea4176691d Added warning for fi }, and not for ) } 2012-11-30 09:25:49 -08:00
Vidar Holen
f7be39cb5f Added better malformed parsing messages 2012-11-29 22:26:45 -08:00
Vidar Holen
c2b9c1ff2a Compile with -O9 2012-11-29 22:26:13 -08:00
Vidar Holen
1e3b429abe Check for tr hello world 2012-11-29 20:11:47 -08:00
Vidar Holen
b718e5f108 Parser help with globs, fixed message for grep foo\* 2012-11-29 19:20:44 -08:00
Vidar Holen
1bc6086aec Added check for find / -exec foo && bar \; 2012-11-28 22:21:58 -08:00
Vidar Holen
3308ac9173 Warning for dirname/basename 2012-11-28 21:06:58 -08:00
Vidar Holen
089537afed Added parsing support for $'..', which also fixed bug in \` 2012-11-28 20:56:27 -08:00
Vidar Holen
beafb9284a Added support for process substitution 2012-11-28 20:39:27 -08:00
Vidar Holen
8cf899300d Added error for cat << (foo) 2012-11-28 19:21:11 -08:00
Vidar Holen
5d408875f1 Added [[ op -v and -R 2012-11-28 14:44:51 -08:00
Vidar Holen
7d7624252b Added check for for f in $(cat foo) 2012-11-28 11:38:54 -08:00
Vidar Holen
3b1ec7f84e Check for [[ $foo =~ '.*' ]] 2012-11-28 00:16:08 -08:00
Vidar Holen
01d3e5e858 Fixed unquoted error for [ ! $(foo) ] 2012-11-27 23:59:08 -08:00
Vidar Holen
b2c1c103c1 Added check for $(expr 3 + 2) 2012-11-27 23:55:08 -08:00
Vidar Holen
55ea991da7 Misspelled 'deprecated' 2012-11-27 23:42:50 -08:00
Vidar Holen
8db22b02e1 Added check for while $((n>3)); do .. 2012-11-27 23:38:44 -08:00
Vidar Holen
396541f3c2 Stop treating backticks as literals. 2012-11-27 23:11:59 -08:00
Vidar Holen
0cbbee7b89 Added slightly better ${..} parsing 2012-11-27 23:05:39 -08:00
Vidar Holen
77a3e3b331 Fixed incorrectly calling [ -z $foo ] a tautology. 2012-11-27 20:40:13 -08:00
Vidar Holen
2b2ee0a897 Suggest IFS='' as style for assigning empty vars. 2012-11-27 20:27:07 -08:00
Vidar Holen
e8a2ac09c7 Added check for grep foo* 2012-11-27 20:26:41 -08:00
Vidar Holen
96c8a01017 Added check for find / -name *.php 2012-11-27 20:10:54 -08:00
Vidar Holen
e2a6ffbea4 Added check for 'foo(a,b) {', support 'function foo {' 2012-11-27 19:45:32 -08:00
Vidar Holen
807e56355d Punctuated message. 2012-11-27 01:48:51 -08:00
Vidar Holen
bb7e844125 Added better message for missing ]/]] 2012-11-27 01:28:42 -08:00
Vidar Holen
100fff4835 Added grep | sed check like existing grep | awk. 2012-11-27 01:21:14 -08:00
Vidar Holen
1aeff4f955 Added more robust a=cat foo | grep bar checker 2012-11-27 01:05:32 -08:00
Vidar Holen
adfdc0a627 Added check for a=ls -l 2012-11-27 00:48:09 -08:00
Vidar Holen
a8715d2d5f Added check for A=foo | grep bar 2012-11-27 00:41:10 -08:00
Vidar Holen
0ca6d0f6cc Added extglobs as splitting words 2012-11-27 00:32:00 -08:00
Vidar Holen
131b9f0517 Added checks for tr a-z A-Z and [asdf] 2012-11-27 00:28:47 -08:00
Vidar Holen
ba5bb488d1 Case statements are now rightfully unquotable contexts 2012-11-27 00:11:23 -08:00
Vidar Holen
2052adffef Even more robust then/fi/do/done feedback 2012-11-27 00:08:24 -08:00
Vidar Holen
8cf02e60af More robust fi/done mixup reporting 2012-11-26 23:50:00 -08:00
Vidar Holen
2ea4711ff4 Added check, for f in 'find /'; do .. 2012-11-26 22:58:30 -08:00
Vidar Holen
ef332217a1 Check for if[ foo ] 2012-11-26 22:49:23 -08:00
Vidar Holen
34690ad3db Added more helpful message for 'if [ grep .. ]' 2012-11-26 22:23:40 -08:00
Vidar Holen
7025ebd633 Made unquoted $(..) check more robust 2012-11-26 21:52:47 -08:00
Vidar Holen
211c923f8b Replaced common commands from /bin to posix utility list 2012-11-26 21:22:20 -08:00
Vidar Holen
4a803d2e48 Removed trailing whitespace 2012-11-26 20:43:19 -08:00
Vidar Holen
f4afb9a88f Added check for constant [[]] expression, e.g. [[ a == b ]] 2012-11-26 20:42:10 -08:00
Vidar Holen
648090af31 Added warnings for then/fi/do/done treated literally. 2012-11-25 10:49:21 -08:00
Vidar Holen
21262399cc Added a check for spurious }s 2012-11-25 00:42:59 -08:00
Vidar Holen
d58bd400ea Added check for echo $foo | wc -c 2012-11-25 00:07:53 -08:00
Vidar Holen
aaf5ac6f8f Added check for echo $a | sed s/foo/bar/g 2012-11-24 20:38:37 -08:00
Vidar Holen
aae87fc030 Added better space/glob checks 2012-11-24 14:41:17 -08:00
Vidar Holen
0d34f2dedd Added ulimit to test script because lol debugging 2012-11-19 23:24:24 -08:00
Vidar Holen
807ecbd038 Added extglob support that actually works 2012-11-19 23:20:01 -08:00
Vidar Holen
5100bc0989 Added check for [[ a != foo || a != bar ]], and same for (( )) 2012-11-19 22:54:55 -08:00
Vidar Holen
3f3ca2789b Moved Eq Token instance to AST where it belongs 2012-11-19 22:32:55 -08:00
Vidar Holen
0e4f8a763f Added extglob support 2012-11-19 22:27:44 -08:00
Vidar Holen
6977963124 Added checks for multiple pipe combinations. 2012-11-19 21:52:26 -08:00
Vidar Holen
7e3712f853 Added the regex lib as a dependency 2012-11-17 12:09:34 -08:00
Vidar Holen
2fb011aa9b Typo 2012-11-17 11:48:16 -08:00
Vidar Holen
090b94161d Fixed incorrect warning for foo=$3 2012-11-17 10:53:39 -08:00
Vidar Holen
ecccc7a6b7 Added some more punctuation to messages. 2012-11-17 10:21:34 -08:00
Vidar Holen
0141bd812b Give it some attitude 2012-11-16 23:04:40 -08:00
Vidar Holen
9eac0bfab9 Homogenized punctuation across messages. 2012-11-16 22:20:35 -08:00
Vidar Holen
45d5896cf8 More helpful errors for partial if statements 2012-11-16 21:30:52 -08:00
Vidar Holen
89b0168254 Fixed incorrect errors on [[ $1 ]] 2012-11-16 21:01:26 -08:00
Vidar Holen
19a7698785 Accidentally made quackCheck non-executable 2012-11-16 20:40:17 -08:00
Vidar Holen
07b29dceb4 Never mind quackCheck 2012-11-16 19:43:41 -08:00
Vidar Holen
258a13721e Added readme and licenses 2012-11-16 19:43:05 -08:00
Vidar Holen
a7a19fa366 Support a+=foo 2012-11-16 18:53:54 -08:00
Vidar Holen
851de930c0 Removed bash, true and false from [ command ] check, since these could be values 2012-11-16 11:15:26 -08:00
Vidar Holen
a172c8a8b9 Fixed $(( ! n )) and incorrect warning on $(($?)) 2012-11-16 11:07:10 -08:00
Vidar Holen
900c6d01d4 Cleaned up analytics notes 2012-11-16 10:22:04 -08:00
Vidar Holen
2581be14e4 Moved AST into its own file 2012-11-16 10:12:51 -08:00
Vidar Holen
5faf8e7141 Added check for printf "$var" 2012-11-16 09:53:35 -08:00
Vidar Holen
686c895858 Added check for [[ foo == $bar ]] 2012-11-15 23:43:57 -08:00
Vidar Holen
a2cc44a04d Added check for $(($n)) 2012-11-15 23:32:45 -08:00
Vidar Holen
ad9db04856 Fixed incorrect n=1 & n=foo$n and same for $((n++)) 2012-11-15 23:23:08 -08:00
Vidar Holen
5d26f627cf Rewrote the horrible analyze code 2012-11-15 22:19:06 -08:00
Vidar Holen
61baf730e0 Added support for parsing arithmetic context 2012-11-15 21:38:36 -08:00
Vidar Holen
38c5c6f847 Added warning for {1..$N} 2012-11-08 21:55:24 -08:00
Vidar Holen
7dbae12c7e Fixed bugs related to groupings in conditions 2012-11-08 21:48:32 -08:00
Vidar Holen
33913366b1 Fixed bug in allModifiedVariables 2012-11-08 21:08:20 -08:00
Vidar Holen
f9f2982c9f Added check for [ a==b ] 2012-11-08 20:43:51 -08:00
Vidar Holen
947ae519a2 Fixed [ grep foo bar ] warning not working 2012-11-08 20:28:06 -08:00
Vidar Holen
97e886e6dd Added more [[]]-related checks 2012-11-08 20:19:34 -08:00
Vidar Holen
977cf427ca Added parser for [[]]/[] with associated errors 2012-11-08 14:39:14 -08:00
Vidar Holen
99e765ff34 Minor text modifications 2012-11-07 18:27:12 -08:00
Vidar Holen
de31835676 Added reason in messages about subshells 2012-11-07 16:36:18 -08:00
Vidar Holen
7e3a20c14a Added a json interface 2012-11-06 21:55:46 -08:00
Vidar Holen
9ca7d57780 Renamed much of the ShellCheck.Simple interface 2012-11-06 13:26:25 -08:00
Vidar Holen
e264f64266 Renamed from codename Shpell to final name ShellCheck. 2012-11-06 11:31:53 -08:00
Vidar Holen
45b98f408c Ditched the stunted concept and added better warnings 2012-11-05 20:50:00 -08:00
Vidar Holen
a25cc75afa Check for attempted expansion in single quoted variables 2012-11-05 20:03:14 -08:00
Vidar Holen
0c0b386cf3 Warnings for unquoted positional parameters 2012-11-05 19:00:40 -08:00
Vidar Holen
ce46defec8 Merged DollarVariable and DollarBraced, and made the $* test more general 2012-11-05 18:45:23 -08:00
Vidar Holen
90c1b63790 Added read/export as variable modifying commands for subshells 2012-11-05 18:33:45 -08:00
Vidar Holen
e251e4a04f Made Makefile marginally less sucky 2012-11-05 17:37:48 -08:00
Vidar Holen
c3f62aaad6 Revert ""modified" -> "set" for subshell var messages"
Yeah no it was better before
This reverts commit d2b258434d.
2012-11-05 10:30:36 -08:00
Vidar Holen
da8ab3322c Added subshell variable detection cases 2012-11-05 10:29:39 -08:00
Vidar Holen
d2b258434d "modified" -> "set" for subshell var messages 2012-11-05 10:29:06 -08:00
Vidar Holen
0fda08b36e Fixed missing Alive detection in current scope 2012-11-05 10:24:52 -08:00
Vidar Holen
a14d0a8790 Basic subshell detection in place 2012-11-05 09:26:27 -08:00
Vidar Holen
5fef47a8d4 Added support for stack based analysis 2012-11-05 08:10:16 -08:00
Vidar Holen
fb8e843717 Fixed position of &; message 2012-11-05 01:46:01 -08:00
Vidar Holen
1bf382e370 Less sentience 2012-11-05 01:42:36 -08:00
Vidar Holen
ae175bbdf4 Show 'eof' instead of blank string in unexpected token messages 2012-11-05 01:39:37 -08:00
Vidar Holen
9140544176 I'm tired of seeing this garbage in the changelog 2012-11-05 01:34:06 -08:00
Vidar Holen
5de7a39f3e Added error for 2>&1 > lol 2012-11-05 01:32:36 -08:00
Vidar Holen
af1517146e Upgraded for f in $(ls ..) to Error. I mean, come on. 2012-11-05 01:09:43 -08:00
Vidar Holen
7bc732b2a2 Added and fixed checkes related to "$@"/$* 2012-11-05 01:08:00 -08:00
Vidar Holen
98f5c48d47 Made lonely dollar not match $'..' 2012-11-05 00:25:58 -08:00
Vidar Holen
3f630d3faa Fixed irrelevant mixup in irrelevant command to make my joke better 2012-11-04 22:17:17 -08:00
Vidar Holen
fdd2110437 Build shpell before running tests, in case of compiler errors 2012-11-04 22:15:06 -08:00
Vidar Holen
69183f6609 Added warning for a && b || c 2012-11-04 22:14:47 -08:00
Vidar Holen
67d27ea42d Tweaked some messages and added more badcases 2012-11-04 21:44:48 -08:00
Vidar Holen
279e972b61 For * in ls case now uses $(..) 2012-11-04 20:31:38 -08:00
Vidar Holen
c6a05179e0 Added Makefile and horrifying test framework 2012-11-04 20:29:21 -08:00
Vidar Holen
4557f4acd3 Made tool seem less sentient 2012-11-04 19:42:53 -08:00
Vidar Holen
e6edffa8d1 Fixed off by one preventing printing of last line 2012-11-04 19:42:32 -08:00
Vidar Holen
a92598c372 Fixed up the wannabe unit tests 2012-11-04 19:36:38 -08:00
Vidar Holen
22ae83e372 Gave Parsec errors proper positioning info 2012-11-04 18:58:34 -08:00
Vidar Holen
d5587dd104 Fixed the position of the 'then;' errors 2012-11-04 18:18:10 -08:00
Vidar Holen
a7afa32075 Added some test cases, not all of which are supported yet 2012-11-04 18:10:51 -08:00
Vidar Holen
cde1e2966f Minor reformatting 2012-11-04 18:07:46 -08:00
Vidar Holen
2f5a7be421 Added cute simplified API plus a CLI frontend 2012-11-04 18:02:51 -08:00
Vidar Holen
17633aa2a8 Moved analytics out of the ParsecT monad and into its own module 2012-11-04 16:20:11 -08:00
Vidar Holen
71a571b083 Moar errors 2012-11-04 00:32:54 -07:00
Vidar Holen
9bc0d57b14 Added warning for &; 2012-11-04 00:19:13 -07:00
Vidar Holen
bc810e9eab Added check for using a file in the same pipeline as a redirect 2012-11-03 21:48:52 -07:00
Vidar Holen
54de7e7e1c Added warnings for then;, else; 2012-11-03 16:27:17 -07:00
Vidar Holen
041581b05f Rewrote the whole Annotation thing. Added quickCheck tests. 2012-11-03 16:11:12 -07:00
45 changed files with 14016 additions and 934 deletions

1
.ghci Normal file
View File

@@ -0,0 +1 @@
:set -idist/build/autogen -isrc

27
.github/ISSUE_TEMPLATE.md vendored Normal file
View File

@@ -0,0 +1,27 @@
#### For bugs
- 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 shellcheck.net and verified that this is still a problem on the latest commit
#### For new checks and feature suggestions
- [ ] 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 the problem:
```sh
#!/your/interpreter
your script here
```
#### Here's what shellcheck currently says:
#### Here's what I wanted or expected to see:

25
.gitignore vendored Normal file
View File

@@ -0,0 +1,25 @@
# Created by https://www.gitignore.io
### Haskell ###
dist
cabal-dev
*.o
*.hi
*.chi
*.chs.h
.virtualenv
.hsenv
.cabal-sandbox/
cabal.sandbox.config
cabal.config
.stack-work
dist-newstyle/
.ghc.environment.*
cabal.project.local
### Snap ###
/snap/.snapcraft/
/stage/
/parts/
/prime/
*.snap

50
.prepare_deploy Executable file
View File

@@ -0,0 +1,50 @@
#!/bin/bash
# This script packages up Travis compiled binaries
set -ex
shopt -s nullglob
cd deploy
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 file in ./*.exe
do
zip "${file%.*}.zip" README.txt LICENSE.txt "$file"
done
for file in *.linux-x86_64
do
base="${file%.*}"
cp "$file" "shellcheck"
tar -cJf "$base.linux.x86_64.tar.xz" --transform="s:^:$base/:" README.txt LICENSE.txt shellcheck
rm "shellcheck"
done
for file in *.linux-armv6hf
do
base="${file%.*}"
cp "$file" "shellcheck"
tar -cJf "$base.linux.armv6hf.tar.xz" --transform="s:^:$base/:" README.txt LICENSE.txt shellcheck
rm "shellcheck"
done
for file in ./*
do
sha512sum "$file" > "$file.sha512sum"
done

14
.snapsquid.conf Normal file
View File

@@ -0,0 +1,14 @@
# In 2015, cabal-install had a http bug triggered when proxies didn't keep
# the connection open. This version made it into Ubuntu Xenial as used by
# Snapcraft. In June 2018, Snapcraft's proxy started triggering this bug.
#
# https://bugs.launchpad.net/launchpad-buildd/+bug/1797809
#
# Workaround: add more proxy
visible_hostname localhost
http_port 8888
cache_peer 10.10.10.1 parent 8222 0 no-query default
cache_peer_domain localhost !.internal
http_access allow all

80
.travis.yml Normal file
View File

@@ -0,0 +1,80 @@
sudo: required
language: sh
services:
- docker
before_install:
- DOCKER_BASE="$DOCKER_USERNAME/shellcheck"
- DOCKER_BUILDS=""
- TAGS=""
- test "$TRAVIS_BRANCH" = master && TAGS="$TAGS latest" || true
- test -n "$TRAVIS_TAG" && TAGS="$TAGS stable $TRAVIS_TAG" || true
- echo "Tags are $TAGS"
script:
- mkdir deploy
# Remove all tests to reduce binary size
- ./striptests
# Linux Docker image
- name="$DOCKER_BASE"
- DOCKER_BUILDS="$DOCKER_BUILDS $name"
- docker build -t "$name:current" .
- docker run "$name:current" --version
- printf '%s\n' "#!/bin/sh" "echo 'hello world'" > myscript
- docker run -v "$PWD:/mnt" "$name:current" myscript
# Copy static executable from docker image
- id=$(docker create "$name:current")
- docker cp "$id:/bin/shellcheck" "shellcheck"
- docker rm "$id"
- ls -l shellcheck
- ./shellcheck myscript
- for tag in $TAGS; do cp "shellcheck" "deploy/shellcheck-$tag.linux-x86_64"; done
# Linux Alpine based Docker image
- name="$DOCKER_BASE-alpine"
- DOCKER_BUILDS="$DOCKER_BUILDS $name"
- sed -e '/DELETE-MARKER/,$d' Dockerfile > Dockerfile.alpine
- docker build -f Dockerfile.alpine -t "$name:current" .
- docker run "$name:current" sh -c 'shellcheck --version'
# Linux armv6hf static executable
- docker run -v "$PWD:/mnt" koalaman/armv6hf-builder -c 'compile-shellcheck'
- for tag in $TAGS; do cp "shellcheck" "deploy/shellcheck-$tag.linux-armv6hf"; done
- rm -f shellcheck || true
# Windows .exe
- docker run --user="$UID" -v "$PWD:/appdata" koalaman/winghc cuib
- for tag in $TAGS; do cp "dist/build/ShellCheck/shellcheck.exe" "deploy/shellcheck-$tag.exe"; done
- rm -rf dist shellcheck || true
# Misc packaging
- ./.prepare_deploy
after_success:
- docker login -u="$DOCKER_USERNAME" -p="$DOCKER_PASSWORD"
- for repo in $DOCKER_BUILDS;
do
for tag in $TAGS;
do
echo "Deploying $repo:current as $repo:$tag...";
docker tag "$repo:current" "$repo:$tag" || exit 1;
docker push "$repo:$tag" || exit 1;
done;
done;
after_failure:
- id
- pwd
- df -h
- find . -name '*.log' -type f -exec grep "" /dev/null {} +
- find . -ls
deploy:
provider: gcs
skip_cleanup: true
access_key_id: GOOG7MDN7WEH6IIGBDCA
secret_access_key:
secure: Bcx2cT0/E2ikj7sdamVq52xlLZF9dz9ojGPtoKfPyQhkkZa+McVI4xgUSuyyoSxyKj77sofx2y8m6PJYYumT4g5hREV1tfeUkl0J2DQFMbGDYEt7kxVkXCxojNvhHwTzLFv0ezstrxWWxQm81BfQQ4U9lggRXtndAP4czZnOeHPINPSiue1QNwRAEw05r5UoIUJXy/5xyUrjIxn381pAs+gJqP2COeN9kTKYH53nS/AAws29RprfZFnPlo7xxWmcjRcdS5KPdGXI/c6tQp5zl2iTh510VC1PN2w1Wvnn/oNWhiNdqPyVDsojIX5+sS3nejzJA+KFMxXSBlyXIY3wPpS/MdscU79X6Q5f9ivsFfsm7gNBmxHUPNn0HAvU4ROT/CCE9j6jSbs5PC7QBo3CK4++jxAwE/pd9HUc2rs3k0ofx3rgveJ7txpy5yPKfwIIBi98kVKlC4w7dLvNTOfjW1Imt2yH87XTfsE0UIG9st1WII6s4l/WgBx2GuwKdt6+3QUYiAlCFckkxWi+fAvpHZUEL43Qxub5fN+ZV7Zib1n7opchH4QKGBb6/y0WaDCmtCfu0lppoe/TH6saOTjDFj67NJSElK6ZDxGZ3uw4R+ret2gm6WRKT2Oeub8J33VzSa7VkmFpMPrAAfPa9N1Z4ewBLoTmvxSg2A0dDrCdJio=
bucket: shellcheck
local-dir: deploy
on:
repo: koalaman/shellcheck
all_branches: true

364
CHANGELOG.md Normal file
View File

@@ -0,0 +1,364 @@
## Since previous release
### Added
- Preliminary support for fix suggestions
## 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 deprected 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 delimters 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

69
Dockerfile Normal file
View File

@@ -0,0 +1,69 @@
# Build-only image
FROM ubuntu:18.04 AS build
USER root
WORKDIR /opt/shellCheck
# Install OS deps, including GHC from HVR-PPA
# https://launchpad.net/~hvr/+archive/ubuntu/ghc
RUN apt-get -yq update \
&& apt-get -yq install software-properties-common \
&& apt-add-repository -y "ppa:hvr/ghc" \
&& apt-get -yq update \
&& apt-get -yq install cabal-install-2.4 ghc-8.4.3 pandoc \
&& rm -rf /var/lib/apt/lists/*
ENV PATH="/opt/ghc/bin:${PATH}"
# Use gold linker and check tools versions
RUN ln -s $(which ld.gold) /usr/local/bin/ld && \
cabal --version \
&& ghc --version \
&& ld --version
# Install Haskell deps
# (This is a separate copy/run so that source changes don't require rebuilding)
#
# We also patch regex-tdfa and aeson removing hard-coded -O2 flag.
# This makes compilation faster and binary smaller.
# Performance loss is unnoticeable for ShellCheck
#
# Remember to update versions, once in a while.
COPY ShellCheck.cabal ./
RUN cabal update && \
cabal get regex-tdfa-1.2.3.1 && sed -i 's/-O2//' regex-tdfa-1.2.3.1/regex-tdfa.cabal && \
cabal get aeson-1.4.0.0 && sed -i 's/-O2//' aeson-1.4.0.0/aeson.cabal && \
echo 'packages: . regex-tdfa-1.2.3.1 aeson-1.4.0.0 > cabal.project' && \
cabal new-build --dependencies-only \
--disable-executable-dynamic --enable-split-sections --disable-tests
# Copy source and build it
COPY LICENSE Setup.hs shellcheck.hs shellcheck.1.md ./
COPY src src
COPY test test
# This SED is the only "nastyness" we have to do
# Hopefully soon we could add per-component ld-options to cabal.project
RUN sed -i 's/-- STATIC/ld-options: -static -pthread -Wl,--gc-sections/' ShellCheck.cabal && \
cat ShellCheck.cabal && \
cabal new-build \
--disable-executable-dynamic --enable-split-sections --disable-tests && \
cp $(find dist-newstyle -type f -name shellcheck) . && \
strip --strip-all shellcheck && \
file shellcheck && \
ls -l shellcheck
RUN mkdir -p /out/bin && \
cp shellcheck /out/bin/
# Resulting Alpine image
FROM alpine:latest
LABEL maintainer="Vidar Holen <vidar@vidarholen.net>"
COPY --from=build /out /
# DELETE-MARKER (Remove everything below to keep the alpine image)
# Resulting ShellCheck image
FROM scratch
LABEL maintainer="Vidar Holen <vidar@vidarholen.net>"
WORKDIR /mnt
COPY --from=build /out /
ENTRYPOINT ["/bin/shellcheck"]

684
LICENSE Normal file
View File

@@ -0,0 +1,684 @@
Employer mandated disclaimer:
I am providing code in the repository to you under an open source license.
Because this is my personal repository, the license you receive to my code is
from me and other individual contributors, and not my employer (Facebook).
- Vidar "koala_man" Holen
----
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/philosophy/why-not-lgpl.html>.

461
README.md Normal file
View File

@@ -0,0 +1,461 @@
[![Build Status](https://travis-ci.org/koalaman/shellcheck.svg?branch=master)](https://travis-ci.org/koalaman/shellcheck)
# 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)
- [Travis CI](#travis-ci)
- [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)
## 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).
* Atom, through [Linter](https://github.com/AtomLinter/linter-shellcheck).
* 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.
ShellCheck makes canonical use of exit codes, and 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:
apt-get install shellcheck
On Arch Linux based distros:
pacman -S shellcheck
or get the dependency free [shellcheck-static](https://aur.archlinux.org/packages/shellcheck-static/) from the AUR.
On Gentoo based distros:
emerge --ask shellcheck
On EPEL based distros:
yum -y install epel-release
yum install ShellCheck
On Fedora based distros:
dnf install ShellCheck
On FreeBSD:
pkg install hs-ShellCheck
On OS X with homebrew:
brew 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 [scoop](http://scoop.sh)):
scoop install shellcheck
From Snap Store:
snap install --channel=edge shellcheck
From Docker Hub:
```sh
docker pull koalaman/shellcheck:stable # Or :v0.4.7 for that version, or :latest for daily builds
docker run -v "$PWD:/mnt" koalaman/shellcheck myscript
```
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.
Alternatively, you can download pre-compiled binaries for the latest release here:
* [Linux, x86_64](https://storage.googleapis.com/shellcheck/shellcheck-stable.linux.x86_64.tar.xz) (statically linked)
* [Linux, armv6hf](https://storage.googleapis.com/shellcheck/shellcheck-stable.linux.armv6hf.tar.xz), i.e. Raspberry Pi (statically linked)
* [Windows, x86](https://storage.googleapis.com/shellcheck/shellcheck-stable.zip)
or see the [storage bucket listing](https://shellcheck.storage.googleapis.com/index.html) for checksums, older versions and the latest daily builds.
Distro packages already come with a `man` page. If you are building from source, it can be installed with:
pandoc -s -t man shellcheck.1.md -o shellcheck.1
sudo mv shellcheck.1 /usr/share/man/man1
## 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 the latest release, follow the steps to install the shellcheck binary, bellow.
## Installing the shellcheck binary
*Pre-requisite*: the program 'xz' needs to be installed on the system.
To install it on debian/ubuntu/linux mint, run `apt install xz-utils`.
To install it on Redhat/Fedora/CentOS, run `yum -y install xz`.
```bash
export scversion="stable" # or "v0.4.7", or "latest"
wget "https://storage.googleapis.com/shellcheck/shellcheck-${scversion}.linux.x86_64.tar.xz"
tar --xz -xvf shellcheck-"${scversion}".linux.x86_64.tar.xz
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 cask
brew cask install haskell-platform
cabal 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
Or if you intend to run the tests:
$ cabal install --enable-tests
This will compile ShellCheck and install it to your `~/.cabal/bin` directory.
Add this directory to your `PATH` (for bash, add this to your `~/.bashrc`):
```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`:
> chcp 65001
Active code page: 65001
In Powershell ISE, you may need to additionally update the output encoding:
> [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
```
### 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 ((..))
```
### 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
```
### 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
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
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-2018, Vidar 'koala_man' Holen 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)!

81
Setup.hs Normal file
View File

@@ -0,0 +1,81 @@
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -Wall #-}
module Main (main) where
import Distribution.PackageDescription (
HookedBuildInfo,
emptyHookedBuildInfo )
import Distribution.Simple (
Args,
UserHooks ( preSDist ),
defaultMainWithHooks,
simpleUserHooks )
import Distribution.Simple.Setup ( SDistFlags )
import System.Process ( system )
import System.Directory ( doesFileExist, getModificationTime )
#ifndef MIN_VERSION_cabal_doctest
#define MIN_VERSION_cabal_doctest(x,y,z) 0
#endif
#if MIN_VERSION_cabal_doctest(1,0,0)
import Distribution.Extra.Doctest ( addDoctestsUserHook )
main :: IO ()
main = defaultMainWithHooks $ addDoctestsUserHook "doctests" myHooks
where
myHooks = simpleUserHooks { preSDist = myPreSDist }
#else
#ifdef MIN_VERSION_Cabal
-- If the macro is defined, we have new cabal-install,
-- but for some reason we don't have cabal-doctest in package-db
--
-- Probably we are running cabal sdist, when otherwise using new-build
-- workflow
#warning You are configuring this package without cabal-doctest installed. \
The doctests test-suite will not work as a result. \
To fix this, install cabal-doctest before configuring.
#endif
main :: IO ()
main = defaultMainWithHooks myHooks
where
myHooks = simpleUserHooks { preSDist = myPreSDist }
#endif
-- | This hook will be executed before e.g. @cabal sdist@. It runs
-- pandoc to create the man page from shellcheck.1.md. If the pandoc
-- command is not found, this will fail with an error message:
--
-- /bin/sh: pandoc: command not found
--
-- Since the man page is listed in the Extra-Source-Files section of
-- our cabal file, a failure here should result in a failure to
-- create the distribution tarball (that's a good thing).
--
myPreSDist :: Args -> SDistFlags -> IO HookedBuildInfo
myPreSDist _ _ = do
exists <- doesFileExist "shellcheck.1"
if exists
then do
source <- getModificationTime "shellcheck.1.md"
target <- getModificationTime "shellcheck.1"
if target < source
then makeManPage
else putStrLn "shellcheck.1 is more recent than shellcheck.1.md"
else makeManPage
return emptyHookedBuildInfo
where
makeManPage = do
putStrLn "Building the man page (shellcheck.1) with pandoc..."
putStrLn pandoc_cmd
result <- system pandoc_cmd
putStrLn $ "pandoc exited with " ++ show result
pandoc_cmd = "pandoc -s -t man shellcheck.1.md -o shellcheck.1"

117
ShellCheck.cabal Normal file
View File

@@ -0,0 +1,117 @@
Name: ShellCheck
Version: 0.6.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: Custom
Cabal-Version: >= 1.8
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.
Extra-Source-Files:
-- documentation
README.md
shellcheck.1.md
-- built with a cabal sdist hook
shellcheck.1
custom-setup
setup-depends:
base >= 4 && <5,
directory >= 1.2 && <1.4,
process >= 1.0 && <1.7,
cabal-doctest >= 1.0.6 && <1.1,
Cabal >= 1.10 && <2.5
source-repository head
type: git
location: git://github.com/koalaman/shellcheck.git
library
hs-source-dirs: src
if impl(ghc < 8.0)
build-depends:
semigroups
build-depends:
-- GHC 7.6.3 (base 4.6.0.1) is buggy (#1131, #1119) in optimized mode.
-- Just disable that version entirely to fail fast.
aeson,
base > 4.6.0.1 && < 5,
bytestring,
containers >= 0.5,
deepseq >= 1.4.0.0,
directory,
mtl >= 2.2.1,
parsec,
regex-tdfa,
-- When cabal supports it, move this to setup-depends:
process
exposed-modules:
ShellCheck.AST
ShellCheck.ASTLib
ShellCheck.Analytics
ShellCheck.Analyzer
ShellCheck.AnalyzerLib
ShellCheck.Checker
ShellCheck.Checks.Commands
ShellCheck.Checks.ShellSupport
ShellCheck.Data
ShellCheck.Formatter.Format
ShellCheck.Formatter.CheckStyle
ShellCheck.Formatter.GCC
ShellCheck.Formatter.JSON
ShellCheck.Formatter.TTY
ShellCheck.Interface
ShellCheck.Parser
ShellCheck.Regex
other-modules:
Paths_ShellCheck
executable shellcheck
if impl(ghc < 8.0)
build-depends:
semigroups
build-depends:
aeson,
base >= 4 && < 5,
bytestring,
deepseq >= 1.4.0.0,
ShellCheck,
containers,
directory,
mtl >= 2.2.1,
parsec >= 3.0,
regex-tdfa
main-is: shellcheck.hs
-- Marker to add flags for static linking
-- STATIC
test-suite doctests
type: exitcode-stdio-1.0
main-is: doctests.hs
build-depends:
base,
doctest >= 0.16.0 && <0.17,
QuickCheck >=2.11 && <2.13,
ShellCheck,
template-haskell
x-doctest-options: --fast
ghc-options: -Wall -threaded
hs-source-dirs: test

BIN
doc/emacs-flycheck.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

BIN
doc/terminal.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

BIN
doc/vim-syntastic.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

13
nextnumber Executable file
View File

@@ -0,0 +1,13 @@
#!/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
do
last=$(grep -hv "^prop" ./**/*.hs | grep -Ewo "$i[0-9]{3}" | sort -n | tail -n 1)
echo "Next ${i}xxx: $((last+1))"
done

12
quickrun Executable file
View File

@@ -0,0 +1,12 @@
#!/usr/bin/env bash
# quickrun runs ShellCheck in an interpreted mode.
# This allows testing changes without recompiling.
runghc -isrc -idist/build/autogen shellcheck.hs "$@"
# Note: with new-build you can
#
# % cabal new-run --disable-optimization -- shellcheck "$@"
#
# This does build the executable, but as the optimisation is disabled,
# the build is quite fast.

21
quicktest Executable file
View File

@@ -0,0 +1,21 @@
#!/bin/bash
# shellcheck disable=SC2091
# quicktest runs the ShellCheck unit tests.
# Once `doctests` test executable is build, we can just run it
# This allows running tests without compiling library, which is faster.
# 'cabal test' remains the source of truth.
$(find dist -type f -name doctests)
# Note: if you have build the project with new-build
#
# % cabal new-build -w ghc-8.4.3 --enable-tests
#
# and have cabal-plan installed (e.g. with cabal new-install cabal-plan),
# then you can quicktest with
#
# % $(cabal-plan list-bin doctests)
#
# Once the test executable exists, we can simply run it to perform doctests
# which use GHCi under the hood.

225
shellcheck.1.md Normal file
View File

@@ -0,0 +1,225 @@
% 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 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**.
**-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.
**-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.
**-S**\ *SEVERITY*,\ **--severity=***severity*
: Specify minimum severity of errors to consider. Valid values are *error*,
*warning*, *info* and *style*. The default is *style*.
**-s**\ *shell*,\ **--shell=***shell*
: Specify Bourne shell dialect. Valid values are *sh*, *bash*, *dash* and *ksh*.
The default is to use the file's shebang, or *bash* if the target shell
can't be determined.
**-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`.
# 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>
**json**
: Json is a popular serialization format that is more suitable for web
applications. ShellCheck's json is compact and contains only the bare
minimum.
[
{
"file": "filename",
"line": lineNumber,
"column": columnNumber,
"level": "severitylevel",
"code": errorCode,
"message": "warning message"
},
...
]
# DIRECTIVES
ShellCheck directives can be specified as comments in the shell script
before a 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.
**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`.
**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=2039'.
# 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 follow 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`.
# AUTHOR
ShellCheck is written and maintained by Vidar Holen.
# REPORTING BUGS
Bugs and issues can be reported on GitHub:
https://github.com/koalaman/shellcheck/issues
# COPYRIGHT
Copyright 2012-2015, Vidar Holen.
Licensed under the GNU General Public License version 3 or later,
see https://gnu.org/licenses/gpl.html
# SEE ALSO
sh(1) bash(1)

420
shellcheck.hs Normal file
View File

@@ -0,0 +1,420 @@
{-
Copyright 2012-2015 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 ShellCheck.Checker
import ShellCheck.Data
import ShellCheck.Interface
import ShellCheck.Regex
import qualified ShellCheck.Formatter.CheckStyle
import ShellCheck.Formatter.Format
import qualified ShellCheck.Formatter.GCC
import qualified ShellCheck.Formatter.JSON
import qualified ShellCheck.Formatter.TTY
import Control.Exception
import Control.Monad
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.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,
formatterOptions :: FormatterOptions,
minSeverity :: Severity
}
defaultOptions = Options {
checkSpec = emptyCheckSpec,
externalSources = False,
formatterOptions = newFormatterOptions {
foColorOption = ColorAuto
},
minSeverity = StyleC
}
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 "e" ["exclude"]
(ReqArg (Flag "exclude") "CODE1,CODE2..") "Exclude types of warnings",
Option "f" ["format"]
(ReqArg (Flag "format") "FORMAT") $
"Output format (" ++ formatList ++ ")",
Option "s" ["shell"]
(ReqArg (Flag "shell") "SHELLNAME")
"Specify dialect (sh, bash, dash, ksh)",
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"
]
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" ++ usageInfo usageHeader options
throwError SyntaxFailure
formats :: FormatterOptions -> Map.Map String (IO Formatter)
formats options = Map.fromList [
("checkstyle", ShellCheck.Formatter.CheckStyle.format),
("gcc", ShellCheck.Formatter.GCC.format),
("json", ShellCheck.Formatter.JSON.format),
("tty", ShellCheck.Formatter.TTY.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 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 filter ((== value) . fst) list of
[(name, value)] -> return value
[] -> 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 "version" _ -> do
liftIO printVersion
throwError NoProblems
Flag "externals" _ ->
return options {
externalSources = True
}
Flag "color" color -> do
option <- parseColorOption color
return options {
formatterOptions = (formatterOptions options) {
foColorOption = option
}
}
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
}
}
_ -> 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)
ioInterface options files = do
inputs <- mapM normalize files
cache <- newIORef emptyCache
return SystemInterface {
siReadFile = get cache inputs
}
where
emptyCache :: Map.Map FilePath String
emptyCache = Map.empty
get cache inputs file = do
map <- readIORef cache
case Map.lookup file map of
Just x -> return $ Right x
Nothing -> fetch cache inputs file
fetch cache inputs file = do
ok <- allowable inputs file
if ok
then (do
(contents, shouldCache) <- inputFile file
when shouldCache $
modifyIORef cache $ Map.insert file contents
return $ Right contents
) `catch` handler
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 inputs x =
if externalSources options
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
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"

934
shpell.hs
View File

@@ -1,934 +0,0 @@
{-# LANGUAGE NoMonomorphismRestriction #-}
-- Shpell Check, by Vidar 'koala_man' Holen
-- Sorry about the code. It was a week's worth of hacking.
import Text.Parsec
import Text.Parsec.Pos (initialPos)
import Debug.Trace
import Control.Monad
import Data.Char
import Data.List (isInfixOf, partition, sortBy, intercalate)
import qualified Control.Monad.State as Ms
import Data.Maybe
import Prelude hiding (readList)
import System.IO
backslash = char '\\'
linefeed = char '\n'
singleQuote = char '\''
doubleQuote = char '"'
variableStart = upper <|> lower <|> oneOf "_"
variableChars = upper <|> lower <|> digit <|> oneOf "_"
specialVariable = oneOf "@*#?-$!"
tokenDelimiter = oneOf "&|;<> \t\n"
quotable = oneOf "#|&;<>()$`\\ \"'\t\n"
doubleQuotable = oneOf "\"$`"
whitespace = oneOf " \t\n"
linewhitespace = oneOf " \t"
spacing = do
x <- many (many1 linewhitespace <|> (try $ string "\\\n"))
optional readComment
return $ concat x
allspacing = do
spacing
x <- option False ((linefeed <|> carriageReturn) >> return True)
when x allspacing
carriageReturn = do
parseNote ErrorC "Literal carriage return. Run script through tr -d '\\r' "
char '\r'
--------- Message/position annotation on top of user state
data Annotated a = Annotated SourcePos [Note] a deriving (Show, Eq)
data Note = ParseNote SourcePos Severity String | Note Severity String deriving (Show, Eq)
data MessageStack = StackNode Note MessageStack | StackMark String SourcePos MessageStack | StackEmpty
data ParseProblem = ParseProblem SourcePos Severity String deriving (Show, Eq)
data OutputNote = OutputNote SourcePos Severity String deriving (Show, Eq)
data Severity = ErrorC | WarningC | InfoC | StyleC deriving (Show, Eq, Ord)
instance Functor Annotated where
fmap f (Annotated p n a) = Annotated p n (f a)
markStack msg = do
pos <- getPosition
modifyState (StackMark msg pos)
getMessages r (StackMark _ _ s) = (r, s)
getMessages r (StackNode n s) = getMessages (n:r) s
popStack = do
f <- getState
let (notes, stack) = getMessages [] f
putState stack
return notes
-- Store potential parse problems outside of parsec
parseProblem level msg = do
pos <- getPosition
parseProblemAt pos level msg
parseProblemAt pos level msg = do
Ms.modify ((ParseProblem pos level msg):)
pushNote n = modifyState (StackNode n)
parseNote l a = do
pos <- getPosition
parseNoteAt pos l a
parseNoteAt pos l a = pushNote $ ParseNote pos l a
annotated msg parser = do
pos <- getPosition
markStack msg
result <- parser
messages <- popStack
return $ Annotated pos messages result
dropAnnotation (Annotated _ _ s) = s
blankAnnotation pos t = Annotated pos [] t
merge (Annotated pos messages result) = do
mapM pushNote messages
return result
merging p = p >>= merge
getOutputNotes (Annotated p notes _) = map (makeOutputNote p) notes
makeOutputNote _ (ParseNote p l s) = OutputNote p l s
makeOutputNote p (Note l s) = OutputNote p l s
--------- Convenient combinators
thenSkip main follow = do
r <- main
optional follow
return r
disregard x = x >> return ()
reluctantlyTill p end = do -- parse p until end <|> eof matches ahead
(lookAhead ((disregard $ try end) <|> eof) >> return []) <|> do
x <- p
more <- reluctantlyTill p end
return $ x:more
<|> return []
reluctantlyTill1 p end = do
notFollowedBy end
x <- p
more <- reluctantlyTill p end
return $ x:more
attempting rest branch = do
((try branch) >> rest) <|> rest
wasIncluded p = option False (p >> return True)
-- Horrifying AST
data Token = T_AND_IF | T_OR_IF | T_DSEMI | T_Semi | T_DLESS | T_DGREAT | T_LESSAND | T_GREATAND | T_LESSGREAT | T_DLESSDASH | T_CLOBBER | T_If | T_Then | T_Else | T_Elif | T_Fi | T_Do | T_Done | T_Case | T_Esac | T_While | T_Until | T_For | T_Lbrace | T_Rbrace | T_Lparen | T_Rparen | T_Bang | T_In | T_NEWLINE | T_EOF | T_Less | T_Greater | T_SingleQuoted String | T_Literal String | T_NormalWord [Annotated Token] | T_DoubleQuoted [Annotated Token] | T_DollarExpansion [Token] | T_DollarBraced String | T_DollarVariable String | T_DollarArithmetic String | T_BraceExpansion String | T_IoFile Token Token | T_HereDoc Bool Bool String | T_HereString Token | T_FdRedirect String Token | T_Assignment String Token | T_Redirecting [Annotated Token] Token | T_SimpleCommand [Annotated Token] [Annotated Token] | T_Pipeline [Annotated Token] | T_Banged Token | T_AndIf (Annotated Token) (Annotated Token) | T_OrIf (Annotated Token) (Annotated Token) | T_Backgrounded Token | T_IfExpression [([Token],[Token])] [Token] | T_Subshell [Token] | T_BraceGroup [Token] | T_WhileExpression [Token] [Token] | T_UntilExpression [Token] [Token] | T_ForIn String [Token] [Token] | T_CaseExpression Token [([Token],[Token])] |T_Function String Token | T_Command (Annotated Token) | T_Script [Token]
deriving (Show)
extractNotes' list = modifyFlag ((++) $ concatMap getOutputNotes list) >> return ()
extractNotes (T_NormalWord list) = extractNotes' list
extractNotes (T_DoubleQuoted list) = extractNotes' list
extractNotes (T_Redirecting list f) = extractNotes' list
extractNotes (T_Pipeline list) = extractNotes' list
extractNotes (T_Command list) = extractNotes' [list]
extractNotes (T_SimpleCommand list1 list2) = do
extractNotes' list1
extractNotes' list2
extractNotes t = return ()
postMessage level s = Ms.modify $ \(x, l) -> (x, Note level s : l)
warn s = postMessage WarningC s
inform s = postMessage InfoC s
style s = postMessage StyleC s
putFlag v = modifyFlag (const v) >> return ()
getFlag = modifyFlag id
modifyFlag f = do
Ms.modify $ \(x, l) -> (f x, l)
v <- Ms.get
return $ fst v
analyzeScopes f i = mapM (analyzeScope f i)
analyzeScope f i (Annotated pos notes t) = do
v <- getFlag
let (ret, (flag, list)) = Ms.runState (analyze f i t) (v, [])
putFlag flag
return $ Annotated pos (notes++list) ret
analyze f i s@(T_NormalWord list) = do
f s
a <- analyzeScopes f i list
return . i $ T_NormalWord a
analyze f i s@(T_DoubleQuoted list) = do
f s
a <- analyzeScopes f i list
return . i $ T_DoubleQuoted a
analyze f i s@(T_DollarExpansion l) = do
f s
nl <- mapM (analyze f i) l
return . i $ T_DollarExpansion nl
analyze f i s@(T_IoFile op file) = do
f s
a <- analyze f i op
b <- analyze f i file
return . i $ T_IoFile a b
analyze f i s@(T_HereString word) = do
f s
a <- analyze f i word
return . i $ T_HereString a
analyze f i s@(T_FdRedirect v t) = do
f s
a <- analyze f i t
return . i $ T_FdRedirect v a
analyze f i s@(T_Assignment v t) = do
f s
a <- analyze f i t
return . i $ T_Assignment v a
analyze f i s@(T_Redirecting redirs cmd) = do
f s
newRedirs <- analyzeScopes f i redirs
newCmd <- analyze f i $ cmd
return . i $ (T_Redirecting newRedirs newCmd)
analyze f i s@(T_SimpleCommand vars cmds) = do
f s
a <- analyzeScopes f i vars
b <- analyzeScopes f i cmds
return . i $ T_SimpleCommand a b
analyze f i s@(T_Pipeline l) = do
f s
a <- analyzeScopes f i l
return . i $ T_Pipeline a
analyze f i s@(T_Banged l) = do
f s
a <- analyze f i l
return . i $ T_Banged a
analyze f i s@(T_AndIf t u) = do
f s
a <- analyzeScope f i t
b <- analyzeScope f i u
return . i $ T_AndIf a b
analyze f i s@(T_OrIf t u) = do
f s
a <- analyzeScope f i t
b <- analyzeScope f i u
return . i $ T_OrIf a b
analyze f i s@(T_Backgrounded l) = do
f s
a <- analyze f i l
return . i $ T_Backgrounded a
analyze f i s@(T_IfExpression conditions elses) = do
f s
newConds <- mapM (\(c, t) -> do
x <- mapM (analyze f i) c
y <- mapM (analyze f i) t
return (x, y)
) conditions
newElses <- mapM (analyze f i) elses
return . i $ T_IfExpression newConds newElses
analyze f i s@(T_Subshell l) = do
f s
a <- mapM (analyze f i) l
return . i $ T_Subshell a
analyze f i s@(T_BraceGroup l) = do
f s
a <- mapM (analyze f i) l
return . i $ T_BraceGroup a
analyze f i s@(T_WhileExpression c l) = do
f s
a <- mapM (analyze f i) c
b <- mapM (analyze f i) l
return . i $ T_WhileExpression a b
analyze f i s@(T_UntilExpression c l) = do
f s
a <- mapM (analyze f i) c
b <- mapM (analyze f i) l
return . i $ T_UntilExpression a b
analyze f i s@(T_ForIn v w l) = do
f s
a <- mapM (analyze f i) w
b <- mapM (analyze f i) l
return . i $ T_ForIn v a b
analyze f i s@(T_CaseExpression word cases) = do
f s
newWord <- analyze f i word
newCases <- mapM (\(c, t) -> do
x <- mapM (analyze f i) c
y <- mapM (analyze f i) t
return (x, y)
) cases
return . i $ T_CaseExpression newWord newCases
analyze f i s@(T_Script l) = do
f s
a <- mapM (analyze f i) l
return . i $ T_Script a
analyze f i s@(T_Function name body) = do
f s
a <- analyze f i body
return . i $ T_Function name a
analyze f i s@(T_Command c) = do
f s
a <- analyzeScope f i c
return . i $ T_Command a
analyze f i t = do
f t
return . i $ t
doAnalysis f t = fst $ Ms.runState (analyze f id t) ((), [])
explore f d t = fst . snd $ Ms.runState (analyze f id t) (d, [])
transform i t = fst $ Ms.runState (analyze (const $ return ()) i t) ((), [])
findNotes t = explore extractNotes [] t
sortNotes l = sortBy compareNotes l
compareNotes (OutputNote pos1 level1 _) (OutputNote pos2 level2 _) = compare (pos1, level1) (pos2, level2)
findParseNotes l = map (\(ParseProblem p level s) -> OutputNote p level s) l
-- T_UntilExpression [Token] [Token] | T_ForIn String [Token] [Token]
getNotes s =
case rp readScript s of
(Right x, p) -> sortNotes $ (findNotes $ doAllAnalysis x) ++ (findParseNotes p)
(Left _, p) -> sortNotes $ (OutputNote (initialPos "-") ErrorC "Parsing failed"):(findParseNotes p)
readComment = do
char '#'
anyChar `reluctantlyTill` linefeed
readNormalWord = do
x <- many1 readNormalWordPart
return $ T_NormalWord x
readNormalWordPart = readSingleQuoted <|> readDoubleQuoted <|> readDollar <|> readBraced <|> readBackTicked <|> (annotated "normal literal" $ readNormalLiteral)
readSingleQuoted = annotated "single quoted string" $ do
singleQuote
s <- readSingleQuotedPart `reluctantlyTill` singleQuote
singleQuote <?> "End single quoted string"
let string = concat s
return (T_SingleQuoted string) `attempting` do
x <- lookAhead anyChar
when (isAlpha x && isAlpha (last string)) $ parseProblem WarningC "This apostrophe terminated the single quoted string."
readSingleQuotedLiteral = do
singleQuote
strs <- many1 readSingleQuotedPart
singleQuote
return $ concat strs
readSingleQuotedPart =
readSingleEscaped
<|> anyChar `reluctantlyTill1` (singleQuote <|> backslash)
readBackTicked = annotated "backtick expansion" $ do
parseNote StyleC "`..` style expansion is deprecated, use $(..) instead if you want my help"
pos <- getPosition
char '`'
f <- readGenericLiteral (char '`')
char '`' `attempting` (eof >> parseProblemAt pos ErrorC "Can't find terminating backtick for this one")
return $ T_Literal f
readDoubleQuoted = annotated "double quoted string" $ do
doubleQuote
x <- many doubleQuotedPart
doubleQuote <?> "End double quoted"
return $ T_DoubleQuoted x
doubleQuotedPart = readDoubleLiteral <|> readDollar <|> readBackTicked
readDoubleQuotedLiteral = do
doubleQuote
x <- readDoubleLiteral
doubleQuote
return $ dropAnnotation x
readDoubleLiteral = annotated "double literal" $ do
s <- many1 readDoubleLiteralPart
return $ T_Literal (concat s)
readDoubleLiteralPart = do
x <- (readDoubleEscaped <|> (anyChar >>= \x -> return [x])) `reluctantlyTill1` doubleQuotable
return $ concat x
readNormalLiteral = do
s <- many1 readNormalLiteralPart
return $ T_Literal (concat s)
readNormalLiteralPart = do
readNormalEscaped <|> (anyChar `reluctantlyTill1` quotable)
readNormalEscaped = do
backslash
pos <- getPosition
do
next <- (quotable <|> oneOf "?*[]")
return $ if next == '\n' then "" else [next]
<|>
do
next <- anyChar <?> "No character after \\"
parseNoteAt pos WarningC $ "This character doesn't need escaping here, the \\ is ignored"
return [next]
readSingleEscaped = do
s <- backslash
let attempt level p msg = do { try $ parseNote level msg; x <- p; return [s,x]; }
do {
x <- singleQuote;
parseProblem InfoC "Are you trying to escape a single quote? echo 'You'\\''re doing it wrong'.";
return [s,x];
}
<|> attempt InfoC linefeed "You don't break lines with \\ in single quotes, it results in literal backslash-linefeed."
<|> do
x <- anyChar
return [s,x]
readDoubleEscaped = do
bs <- backslash
(linefeed >> return "")
<|> (doubleQuotable >>= return . return)
<|> (anyChar >>= (return . \x -> [bs, x]))
readGenericLiteral endExp = do
strings <- many (readGenericEscaped <|> anyChar `reluctantlyTill1` endExp)
return $ concat strings
readGenericLiteral1 endExp = do
strings <- many1 (readGenericEscaped <|> anyChar `reluctantlyTill1` endExp)
return $ concat strings
readGenericEscaped = do
backslash
x <- anyChar
return $ if x == '\n' then [] else [x]
readBraced = annotated "{1,2..3} expression" $ try $ do
let strip (T_Literal s) = return ("\"" ++ s ++ "\"")
char '{'
str <- many1 ((readDoubleQuotedLiteral >>= (strip )) <|> readGenericLiteral1 (oneOf "}" <|> whitespace))
char '}'
return $ T_BraceExpansion $ concat str
readDollar = readDollarArithmetic <|> readDollarBraced <|> readDollarExpansion <|> readDollarVariable <|> readDollarLonely
readParenLiteralHack = do
strs <- ((anyChar >>= \x -> return [x]) <|> readParenHack) `reluctantlyTill1` (string "))")
return $ concat strs
readParenHack = do
char '('
x <- many anyChar
char ')'
return $ "(" ++ x ++ ")"
readDollarArithmetic = annotated "$(( )) expression" $ do
try (string "$((")
-- TODO
str <- readParenLiteralHack
string "))"
return (T_DollarArithmetic str)
readDollarBraced = annotated "${ } expression" $ do
try (string "${")
-- TODO
str <- readGenericLiteral (char '}')
char '}' <?> "matching }"
return $ (T_DollarBraced str)
readDollarExpansion = annotated "$( )" $ do
try (string "$(")
cmds <- readCompoundList
char ')'
return $ (T_DollarExpansion cmds)
readDollarVariable = annotated "$variable" $ do
let singleCharred p = do
n <- p
return (T_DollarVariable [n]) `attempting` do
pos <- getPosition
num <- lookAhead $ many1 p
parseNoteAt pos ErrorC $ "$" ++ (n:num) ++ " is equivalent to ${" ++ [n] ++ "}"++ num
let positional = singleCharred digit
let special = singleCharred specialVariable
let regular = do
name <- readVariableName
return $ T_DollarVariable (name)
char '$'
positional <|> special <|> regular
readVariableName = do
f <- variableStart
rest <- many variableChars
return (f:rest)
readDollarLonely = annotated "lonely $" $ do
parseNote ErrorC "$ is not used specially and should therefore be escaped"
char '$'
return $ T_Literal "$"
readHereDoc = annotated "here document" $ do
let stripLiteral (T_Literal x) = x
stripLiteral (T_SingleQuoted x) = x
try $ string "<<"
dashed <- (char '-' >> return True) <|> return False
tokenPosition <- getPosition
spacing
(quoted, endToken) <- (readNormalLiteral >>= (\x -> return (False, stripLiteral x)) )
<|> (readDoubleQuotedLiteral >>= return . (\x -> (True, stripLiteral x)))
<|> (readSingleQuotedLiteral >>= return . (\x -> (True, x)))
spacing
hereInfo <- anyChar `reluctantlyTill` (linefeed >> spacing >> (string endToken) >> (disregard whitespace <|> eof))
do
linefeed
spaces <- spacing
verifyHereDoc dashed quoted spaces hereInfo
token <- string endToken
return $ T_FdRedirect "" $ T_HereDoc dashed quoted hereInfo
`attempting` (eof >> debugHereDoc tokenPosition endToken hereInfo)
verifyHereDoc dashed quoted spacing hereInfo = do
when (not dashed && spacing /= "") $ parseNote ErrorC "When using << instead of <<-, the end tokens can't be indented"
when (dashed && filter (/= '\t') spacing /= "" ) $ parseNote ErrorC "When using <<-, you can only indent with tabs"
return ()
debugHereDoc pos endToken doc =
if endToken `isInfixOf` doc
then parseProblemAt pos ErrorC (endToken ++ " was part of the here document, but not by itself at the start of the line")
else if (map toLower endToken) `isInfixOf` (map toLower doc)
then parseProblemAt pos ErrorC (endToken ++ " appears in the here document, but with different case")
else parseProblemAt pos ErrorC ("Couldn't find end token `" ++ endToken ++ "' in the here document ")
readFilename = readNormalWord
readIoFileOp = choice [g_LESSAND, g_GREATAND, g_DGREAT, g_LESSGREAT, g_CLOBBER, string "<" >> return T_Less, string ">" >> return T_Greater ]
readIoFile = do
op <- readIoFileOp
spacing
file <- readFilename
return $ T_FdRedirect "" $ T_IoFile op file
readIoNumber = try $ do
x <- many1 digit
lookAhead readIoFileOp
return x
readIoNumberRedirect = annotated "fd io redirect" $ do
n <- readIoNumber
op <- merging readHereString <|> merging readHereDoc <|> readIoFile
let actualOp = case op of T_FdRedirect "" x -> x
spacing
return $ T_FdRedirect n actualOp
readIoRedirect = annotated "io redirect" $ choice [ merging readIoNumberRedirect, merging readHereString, merging readHereDoc, readIoFile ] `thenSkip` spacing
readRedirectList = many1 readIoRedirect
readHereString = annotated "here string" $ do
try $ string "<<<"
spacing
word <- readNormalWord
return $ T_FdRedirect "" $ T_HereString word
readNewlineList = many1 ((newline <|> carriageReturn) `thenSkip` spacing)
readLineBreak = optional readNewlineList
readSeparatorOp = do
notFollowedBy (g_AND_IF <|> g_DSEMI)
f <- char ';' <|> char '&'
spacing
return f
readSequentialSep = (disregard $ g_Semi >> readLineBreak) <|> (disregard readNewlineList)
readSeparator =
do
separator <- readSeparatorOp
readLineBreak
return separator
<|>
do
readNewlineList
return '\n'
makeSimpleCommand tokens =
let (assignment, rest) = partition (\x -> case dropAnnotation x of T_Assignment _ _ -> True; _ -> False) tokens
in let (redirections, rest2) = partition (\x -> case dropAnnotation x of T_FdRedirect _ _ -> True; _ -> False) rest
in T_Redirecting redirections $ T_SimpleCommand assignment rest2
readSimpleCommand = annotated "simple command" $ do
prefix <- option [] readCmdPrefix
cmd <- option [] $ do { f <- annotated "command name" readCmdName; return [f]; }
when (null prefix && null cmd) $ fail "No command"
if null cmd
then return $ makeSimpleCommand prefix
else do
suffix <- option [] readCmdSuffix
return $ makeSimpleCommand (prefix ++ cmd ++ suffix)
readPipeline = annotated "Pipeline" $ do
notFollowedBy $ try readKeyword
do
g_Bang `thenSkip` spacing
pipe <- readPipeSequence
return $ T_Banged pipe
<|> do
readPipeSequence
readAndOr = (flip (>>=)) (return . T_Command) $ chainr1 readPipeline $ do
pos <- getPosition
op <- g_AND_IF <|> g_OR_IF
readLineBreak
return $ \a b ->
blankAnnotation pos $
case op of T_AND_IF -> T_AndIf a b
T_OR_IF -> T_OrIf a b
readTerm = do
m <- readAndOr
readTerm' m
readTerm' current =
do
sep <- readSeparator
more <- (option T_EOF $ readAndOr)
case more of T_EOF -> return [transformWithSeparator sep current]
_ -> do
list <- readTerm' more
return $ (transformWithSeparator sep current : list)
<|>
return [current]
transformWithSeparator '&' = T_Backgrounded
transformWithSeparator _ = id
readPipeSequence = do
list <- readCommand `sepBy1` (readPipe `thenSkip` (spacing >> readLineBreak))
spacing
return $ T_Pipeline list
readPipe = do
notFollowedBy g_OR_IF
char '|' `thenSkip` spacing
readCommand = (readCompoundCommand <|> readSimpleCommand)
readCmdName = do
f <- readNormalWord
spacing
return f
readCmdWord = do
f <- readNormalWord
spacing
return f
readIfClause = annotated "if statement" $ do
(condition, action) <- readIfPart
elifs <- many readElifPart
elses <- option [] readElsePart
g_Fi
return $ T_IfExpression ((condition, action):elifs) elses
readIfPart = do
g_If
allspacing
condition <- readTerm
g_Then
allspacing
action <- readTerm
return (condition, action)
readElifPart = do
g_Elif
allspacing
condition <- readTerm
g_Then
allspacing
action <- readTerm
return (condition, action)
readElsePart = do
g_Else
allspacing
readTerm
readSubshell = annotated "subshell group" $ do
char '('
allspacing
list <- readCompoundList
allspacing
char ')'
return $ T_Subshell list
readBraceGroup = annotated "brace group" $ do
char '{'
allspacing
list <- readTerm
allspacing
char '}'
return $ T_BraceGroup list
readWhileClause = annotated "while loop" $ do
g_While
condition <- readTerm
statements <- readDoGroup
return $ T_WhileExpression condition statements
readUntilClause = annotated "until loop" $ do
g_Until
condition <- readTerm
statements <- readDoGroup
return $ T_UntilExpression condition statements
readDoGroup = do
pos <- getPosition
g_Do
allspacing
(eof >> return []) <|>
do
commands <- readCompoundList
disregard g_Done <|> eof -- stunted support
return commands
<|> do
parseProblemAt pos ErrorC "Can't find the 'done' for this 'do'"
fail "No done"
readForClause = annotated "for loop" $ do
g_For
spacing
name <- readVariableName
allspacing
values <- readInClause <|> (readSequentialSep >> return [])
group <- readDoGroup <|> (allspacing >> eof >> return []) -- stunted support
return $ T_ForIn name values group
readInClause = do
g_In
things <- (readCmdWord) `reluctantlyTill`
(disregard (g_Semi) <|> disregard linefeed <|> disregard g_Do)
do {
lookAhead (g_Do);
parseNote ErrorC "You need a line feed or semicolon before the 'do' (in Bash)";
} <|> do {
optional $ g_Semi;
disregard allspacing;
}
return things
readCaseClause = annotated "case statement" $ do
g_Case
word <- readNormalWord
spacing
g_In
readLineBreak
list <- readCaseList
g_Esac
return $ T_CaseExpression word list
readCaseList = many readCaseItem
readCaseItem = do
notFollowedBy g_Esac
optional g_Lparen
spacing
pattern <- readPattern
g_Rparen
readLineBreak
list <- ((lookAhead g_DSEMI >> return []) <|> readCompoundList)
(g_DSEMI <|> lookAhead (readLineBreak >> g_Esac))
readLineBreak
return (pattern, list)
readFunctionDefinition = annotated "function definition" $ do
name <- try readFunctionSignature
allspacing
(disregard (lookAhead g_Lbrace) <|> parseProblem ErrorC "Expected a { to open the function definition")
group <- merging readBraceGroup
return $ T_Function name group
readFunctionSignature = do
(optional $ try (string "function " >> parseNote StyleC "Don't use 'function' in front of function definitions"))
name <- readVariableName
spacing
g_Lparen
g_Rparen
return name
readPattern = (readNormalWord `thenSkip` spacing) `sepBy1` (char '|' `thenSkip` spacing)
readCompoundCommand = annotated "compound command" $ do
cmd <- merging $ choice [ readBraceGroup, readSubshell, readWhileClause, readUntilClause, readIfClause, readForClause, readCaseClause, readFunctionDefinition]
spacing
redirs <- many readIoRedirect
return $ T_Redirecting redirs $ cmd
readCompoundList = readTerm
readCmdPrefix = many1 (readIoRedirect <|> readAssignmentWord)
readCmdSuffix = many1 (readIoRedirect <|> annotated "normal word" readCmdWord)
readAssignmentWord = annotated "assignment" $ try $ do
optional (char '$' >> parseNote ErrorC "Don't use $ on the left side of assignments")
variable <- readVariableName
space <- spacing
pos <- getPosition
char '='
space2 <- spacing
value <- readNormalWord
spacing
when (space ++ space2 /= "") $ parseNoteAt pos ErrorC "Don't put spaces around the = in assignments"
return $ T_Assignment variable value
tryToken s t = try (string s >> spacing >> return t)
tryWordToken s t = tryParseWordToken (string s) t `thenSkip` spacing
tryParseWordToken parser t = try (parser >> (lookAhead (eof <|> disregard whitespace))) >> return t
g_AND_IF = tryToken "&&" T_AND_IF
g_OR_IF = tryToken "||" T_OR_IF
g_DSEMI = tryToken ";;" T_DSEMI
g_DLESS = tryToken "<<" T_DLESS
g_DGREAT = tryToken ">>" T_DGREAT
g_LESSAND = tryToken "<&" T_LESSAND
g_GREATAND = tryToken ">&" T_GREATAND
g_LESSGREAT = tryToken "<>" T_LESSGREAT
g_DLESSDASH = tryToken "<<-" T_DLESSDASH
g_CLOBBER = tryToken ">|" T_CLOBBER
g_OPERATOR = g_AND_IF <|> g_OR_IF <|> g_DSEMI <|> g_DLESSDASH <|> g_DLESS <|> g_DGREAT <|> g_LESSAND <|> g_GREATAND <|> g_LESSGREAT
g_If = tryWordToken "if" T_If
g_Then = tryWordToken "then" T_Then
g_Else = tryWordToken "else" T_Else
g_Elif = tryWordToken "elif" T_Elif
g_Fi = tryWordToken "fi" T_Fi
g_Do = tryWordToken "do" T_Do
g_Done = tryWordToken "done" T_Done
g_Case = tryWordToken "case" T_Case
g_Esac = tryWordToken "esac" T_Esac
g_While = tryWordToken "while" T_While
g_Until = tryWordToken "until" T_Until
g_For = tryWordToken "for" T_For
g_In = tryWordToken "in" T_In
g_Lbrace = tryWordToken "{" T_Lbrace
g_Rbrace = tryWordToken "}" T_Rbrace
g_Lparen = tryToken "(" T_Lparen
g_Rparen = tryToken ")" T_Rparen
g_Bang = tryToken "!" T_Bang
g_Semi = do
notFollowedBy g_DSEMI
tryToken ";" T_Semi
readKeyword = choice [ g_Then, g_Else, g_Elif, g_Fi, g_Do, g_Done, g_Esac, g_Rbrace, g_Rparen, g_DSEMI ]
ifParse p t f = do
(lookAhead (try p) >> t) <|> f
wtf = do
x <- many anyChar
parseProblem ErrorC x
readScript = do
do {
allspacing;
commands <- readTerm;
eof <|> (parseProblem WarningC "Stopping here, because I can't parse this command");
return $ T_Script commands;
} <|> do {
parseProblem WarningC "Couldn't read any commands";
wtf;
return T_EOF;
}
shpell s = rp readScript s
rp p s = Ms.runState (runParserT p StackEmpty "-" s) []
-------- Destructively simplify AST
simplify (T_Redirecting [] t) = t
simplify (T_Pipeline [x]) = dropAnnotation x
simplify (T_NormalWord [x]) = dropAnnotation x
simplify t = t
-------- Analytics
doAllAnalysis t = foldl (\v f -> doAnalysis f v) t checks
getAst s = case rp readScript s of (Right parsed, _) -> parsed
getAst2 s = case rp readScript s of (Right parsed, _) -> transform simplify parsed
lol (Right x, _) = x
deadSimple (T_NormalWord l) = [concat (concatMap (deadSimple . dropAnnotation) l)]
deadSimple (T_DoubleQuoted l) = ["\"" ++(concat (concatMap (deadSimple . dropAnnotation) l)) ++ "\""]
deadSimple (T_SingleQuoted s) = [s]
deadSimple (T_DollarVariable _) = ["${VAR}"]
deadSimple (T_DollarBraced _) = ["${VAR}"]
deadSimple (T_DollarArithmetic _) = ["${VAR}"]
deadSimple (T_DollarExpansion _) = ["${VAR}"]
deadSimple (T_Literal x) = [x]
deadSimple (T_SimpleCommand vars words) = concatMap (deadSimple . dropAnnotation) words
deadSimple (T_Redirecting _ foo) = deadSimple foo
deadSimple _ = []
checks = [checkUuoc]
checkUuoc (T_Pipeline ((Annotated _ _ x):_:_)) = case (deadSimple x) of ["cat", _] -> style "UUOC: Instead of 'cat a | b', use 'b < a'"
_ -> return ()
checkUuoc _ = return ()
main = do
s <- getContents
-- case rp readScript s of (Right parsed, _) -> putStrLn . show $ transform simplify parsed
-- (Left x, y) -> putStrLn $ "Can't parse: " ++ (show (x,y))
mapM (putStrLn . show) $ getNotes s

53
snap/snapcraft.yaml Normal file
View File

@@ -0,0 +1,53 @@
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
grade: devel
confinement: strict
apps:
shellcheck:
command: usr/bin/shellcheck
plugs: [home, removable-media]
parts:
shellcheck:
plugin: dump
source: ./
build-packages:
- cabal-install
- squid3
build: |
# See comments in .snapsquid.conf
[ "$http_proxy" ] && {
squid3 -f .snapsquid.conf
export http_proxy="http://localhost:8888"
sleep 3
}
cabal sandbox init
cabal update || cat /var/log/squid/*
cabal install -j
install: |
install -d $SNAPCRAFT_PART_INSTALL/usr/bin
install .cabal-sandbox/bin/shellcheck $SNAPCRAFT_PART_INSTALL/usr/bin

392
src/ShellCheck/AST.hs Normal file
View File

@@ -0,0 +1,392 @@
{-
Copyright 2012-2015 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 #-}
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 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 =
TA_Binary Id String Token Token
| TA_Assignment Id String Token Token
| TA_Variable Id String [Token]
| TA_Expansion Id [Token]
| TA_Sequence Id [Token]
| TA_Trinary Id Token Token Token
| TA_Unary Id String Token
| TC_And Id ConditionType String Token Token
| TC_Binary Id ConditionType String Token Token
| TC_Group Id ConditionType Token
| TC_Nullary Id ConditionType Token
| TC_Or Id ConditionType String Token Token
| TC_Unary Id ConditionType String Token
| TC_Empty Id ConditionType
| T_AND_IF Id
| T_AndIf Id Token Token
| T_Arithmetic Id Token
| T_Array Id [Token]
| T_IndexedElement Id [Token] Token
-- Store the index as string, and parse as arithmetic or string later
| T_UnparsedIndex Id SourcePos String
| T_Assignment Id AssignmentMode String [Token] Token
| T_Backgrounded Id Token
| T_Backticked Id [Token]
| T_Bang Id
| T_Banged Id Token
| T_BraceExpansion Id [Token]
| T_BraceGroup Id [Token]
| T_CLOBBER Id
| T_Case Id
| T_CaseExpression Id Token [(CaseType, [Token], [Token])]
| T_Condition Id ConditionType Token
| T_DGREAT Id
| T_DLESS Id
| T_DLESSDASH Id
| T_DSEMI Id
| T_Do Id
| T_DollarArithmetic Id Token
| T_DollarBraced Id Token
| T_DollarBracket Id Token
| T_DollarDoubleQuoted Id [Token]
| T_DollarExpansion Id [Token]
| T_DollarSingleQuoted Id String
| T_DollarBraceCommandExpansion Id [Token]
| T_Done Id
| T_DoubleQuoted Id [Token]
| T_EOF Id
| T_Elif Id
| T_Else Id
| T_Esac Id
| T_Extglob Id String [Token]
| T_FdRedirect Id String Token
| T_Fi Id
| T_For Id
| T_ForArithmetic Id Token Token Token [Token]
| T_ForIn Id String [Token] [Token]
| T_Function Id FunctionKeyword FunctionParentheses String Token
| T_GREATAND Id
| T_Glob Id String
| T_Greater Id
| T_HereDoc Id Dashed Quoted String [Token]
| T_HereString Id Token
| T_If Id
| T_IfExpression Id [([Token],[Token])] [Token]
| T_In Id
| T_IoFile Id Token Token
| T_IoDuplicate Id Token String
| T_LESSAND Id
| T_LESSGREAT Id
| T_Lbrace Id
| T_Less Id
| T_Literal Id String
| T_Lparen Id
| T_NEWLINE Id
| T_NormalWord Id [Token]
| T_OR_IF Id
| T_OrIf Id Token Token
| T_ParamSubSpecialChar Id String -- e.g. '%' in ${foo%bar} or '/' in ${foo/bar/baz}
| T_Pipeline Id [Token] [Token] -- [Pipe separators] [Commands]
| T_ProcSub Id String [Token]
| T_Rbrace Id
| T_Redirecting Id [Token] Token
| T_Rparen Id
| T_Script Id String [Token]
| T_Select Id
| T_SelectIn Id String [Token] [Token]
| T_Semi Id
| T_SimpleCommand Id [Token] [Token]
| T_SingleQuoted Id String
| T_Subshell Id [Token]
| T_Then Id
| T_Until Id
| T_UntilExpression Id [Token] [Token]
| T_While Id
| T_WhileExpression Id [Token] [Token]
| T_Annotation Id [Annotation] Token
| T_Pipe Id String
| T_CoProc Id (Maybe String) Token
| T_CoProcBody Id Token
| T_Include Id Token
| T_SourceCommand Id Token Token
deriving (Show)
data Annotation =
DisableComment Integer
| SourceOverride String
| ShellOverride String
deriving (Show, Eq)
data ConditionType = DoubleBracket | SingleBracket deriving (Show, Eq)
-- This is an abomination.
tokenEquals :: Token -> Token -> Bool
tokenEquals a b = kludge a == kludge b
where kludge s = Re.subRegex (Re.mkRegex "\\(Id [0-9]+\\)") (show s) "(Id 0)"
instance Eq Token where
(==) = tokenEquals
analyze :: Monad m => (Token -> m ()) -> (Token -> m ()) -> (Token -> m Token) -> Token -> m Token
analyze f g i =
round
where
round t = do
f t
newT <- delve t
g t
i newT
roundAll = mapM round
dl l v = do
x <- roundAll l
return $ v x
dll l m v = do
x <- roundAll l
y <- roundAll m
return $ v x y
d1 t v = do
x <- round t
return $ v x
d2 t1 t2 v = do
x <- round t1
y <- round t2
return $ v x y
delve (T_NormalWord id list) = dl list $ T_NormalWord id
delve (T_DoubleQuoted id list) = dl list $ T_DoubleQuoted id
delve (T_DollarDoubleQuoted id list) = dl list $ T_DollarDoubleQuoted id
delve (T_DollarExpansion id list) = dl list $ T_DollarExpansion id
delve (T_DollarBraceCommandExpansion id list) = dl list $ T_DollarBraceCommandExpansion id
delve (T_BraceExpansion id list) = dl list $ T_BraceExpansion id
delve (T_Backticked id list) = dl list $ T_Backticked id
delve (T_DollarArithmetic id c) = d1 c $ T_DollarArithmetic id
delve (T_DollarBracket id c) = d1 c $ T_DollarBracket id
delve (T_IoFile id op file) = d2 op file $ T_IoFile id
delve (T_IoDuplicate id op num) = d1 op $ \x -> T_IoDuplicate id x num
delve (T_HereString id word) = d1 word $ T_HereString id
delve (T_FdRedirect id v t) = d1 t $ T_FdRedirect id v
delve (T_Assignment id mode var indices value) = do
a <- roundAll indices
b <- round value
return $ T_Assignment id mode var a b
delve (T_Array id t) = dl t $ T_Array id
delve (T_IndexedElement id indices t) = do
a <- roundAll indices
b <- round t
return $ T_IndexedElement id a b
delve (T_Redirecting id redirs cmd) = do
a <- roundAll redirs
b <- round cmd
return $ T_Redirecting id a b
delve (T_SimpleCommand id vars cmds) = dll vars cmds $ T_SimpleCommand id
delve (T_Pipeline id l1 l2) = dll l1 l2 $ T_Pipeline id
delve (T_Banged id l) = d1 l $ T_Banged id
delve (T_AndIf id t u) = d2 t u $ T_AndIf id
delve (T_OrIf id t u) = d2 t u $ T_OrIf id
delve (T_Backgrounded id l) = d1 l $ T_Backgrounded id
delve (T_Subshell id l) = dl l $ T_Subshell id
delve (T_ProcSub id typ l) = dl l $ T_ProcSub id typ
delve (T_Arithmetic id c) = d1 c $ T_Arithmetic id
delve (T_IfExpression id conditions elses) = do
newConds <- mapM (\(c, t) -> do
x <- mapM round c
y <- mapM round t
return (x,y)
) conditions
newElses <- roundAll elses
return $ T_IfExpression id newConds newElses
delve (T_BraceGroup id l) = dl l $ T_BraceGroup id
delve (T_WhileExpression id c l) = dll c l $ T_WhileExpression id
delve (T_UntilExpression id c l) = dll c l $ T_UntilExpression id
delve (T_ForIn id v w l) = dll w l $ T_ForIn id v
delve (T_SelectIn id v w l) = dll w l $ T_SelectIn id v
delve (T_CaseExpression id word cases) = do
newWord <- round word
newCases <- mapM (\(o, c, t) -> do
x <- mapM round c
y <- mapM round t
return (o, x,y)
) cases
return $ T_CaseExpression id newWord newCases
delve (T_ForArithmetic id a b c group) = do
x <- round a
y <- round b
z <- round c
list <- mapM round group
return $ T_ForArithmetic id x y z list
delve (T_Script id s l) = dl l $ T_Script id s
delve (T_Function id a b name body) = d1 body $ T_Function id a b name
delve (T_Condition id typ token) = d1 token $ T_Condition id typ
delve (T_Extglob id str l) = dl l $ T_Extglob id str
delve (T_DollarBraced id op) = d1 op $ T_DollarBraced id
delve (T_HereDoc id d q str l) = dl l $ T_HereDoc id d q str
delve (TC_And id typ str t1 t2) = d2 t1 t2 $ TC_And id typ str
delve (TC_Or id typ str t1 t2) = d2 t1 t2 $ TC_Or id typ str
delve (TC_Group id typ token) = d1 token $ TC_Group id typ
delve (TC_Binary id typ op lhs rhs) = d2 lhs rhs $ TC_Binary id typ op
delve (TC_Unary id typ op token) = d1 token $ TC_Unary id typ op
delve (TC_Nullary id typ token) = d1 token $ TC_Nullary id typ
delve (TA_Binary id op t1 t2) = d2 t1 t2 $ TA_Binary id op
delve (TA_Assignment id op t1 t2) = d2 t1 t2 $ TA_Assignment id op
delve (TA_Unary id op t1) = d1 t1 $ TA_Unary id op
delve (TA_Sequence id l) = dl l $ TA_Sequence id
delve (TA_Trinary id t1 t2 t3) = do
a <- round t1
b <- round t2
c <- round t3
return $ TA_Trinary id a b c
delve (TA_Expansion id t) = dl t $ TA_Expansion id
delve (TA_Variable id str t) = dl t $ TA_Variable id str
delve (T_Annotation id anns t) = d1 t $ T_Annotation id anns
delve (T_CoProc id var body) = d1 body $ T_CoProc id var
delve (T_CoProcBody id t) = d1 t $ T_CoProcBody id
delve (T_Include id script) = d1 script $ T_Include id
delve (T_SourceCommand id includer t_include) = d2 includer t_include $ T_SourceCommand id
delve t = return t
getId :: Token -> Id
getId t = case t of
T_AND_IF id -> id
T_OR_IF id -> id
T_DSEMI id -> id
T_Semi id -> id
T_DLESS id -> id
T_DGREAT id -> id
T_LESSAND id -> id
T_GREATAND id -> id
T_LESSGREAT id -> id
T_DLESSDASH id -> id
T_CLOBBER id -> id
T_If id -> id
T_Then id -> id
T_Else id -> id
T_Elif id -> id
T_Fi id -> id
T_Do id -> id
T_Done id -> id
T_Case id -> id
T_Esac id -> id
T_While id -> id
T_Until id -> id
T_For id -> id
T_Select id -> id
T_Lbrace id -> id
T_Rbrace id -> id
T_Lparen id -> id
T_Rparen id -> id
T_Bang id -> id
T_In id -> id
T_NEWLINE id -> id
T_EOF id -> id
T_Less id -> id
T_Greater id -> id
T_SingleQuoted id _ -> id
T_Literal id _ -> id
T_NormalWord id _ -> id
T_DoubleQuoted id _ -> id
T_DollarExpansion id _ -> id
T_DollarBraced id _ -> id
T_DollarArithmetic id _ -> id
T_BraceExpansion id _ -> id
T_ParamSubSpecialChar id _ -> id
T_DollarBraceCommandExpansion id _ -> id
T_IoFile id _ _ -> id
T_IoDuplicate id _ _ -> id
T_HereDoc id _ _ _ _ -> id
T_HereString id _ -> id
T_FdRedirect id _ _ -> id
T_Assignment id _ _ _ _ -> id
T_Array id _ -> id
T_IndexedElement id _ _ -> id
T_Redirecting id _ _ -> id
T_SimpleCommand id _ _ -> id
T_Pipeline id _ _ -> id
T_Banged id _ -> id
T_AndIf id _ _ -> id
T_OrIf id _ _ -> id
T_Backgrounded id _ -> id
T_IfExpression id _ _ -> id
T_Subshell id _ -> id
T_BraceGroup id _ -> id
T_WhileExpression id _ _ -> id
T_UntilExpression id _ _ -> id
T_ForIn id _ _ _ -> id
T_SelectIn id _ _ _ -> id
T_CaseExpression id _ _ -> id
T_Function id _ _ _ _ -> id
T_Arithmetic id _ -> id
T_Script id _ _ -> id
T_Condition id _ _ -> id
T_Extglob id _ _ -> id
T_Backticked id _ -> id
TC_And id _ _ _ _ -> id
TC_Or id _ _ _ _ -> id
TC_Group id _ _ -> id
TC_Binary id _ _ _ _ -> id
TC_Unary id _ _ _ -> id
TC_Nullary id _ _ -> id
TA_Binary id _ _ _ -> id
TA_Assignment id _ _ _ -> id
TA_Unary id _ _ -> id
TA_Sequence id _ -> id
TA_Trinary id _ _ _ -> id
TA_Expansion id _ -> id
T_ProcSub id _ _ -> id
T_Glob id _ -> id
T_ForArithmetic id _ _ _ _ -> id
T_DollarSingleQuoted id _ -> id
T_DollarDoubleQuoted id _ -> id
T_DollarBracket id _ -> id
T_Annotation id _ _ -> id
T_Pipe id _ -> id
T_CoProc id _ _ -> id
T_CoProcBody id _ -> id
T_Include id _ -> id
T_SourceCommand id _ _ -> id
T_UnparsedIndex id _ _ -> id
TC_Empty id _ -> id
TA_Variable 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)

492
src/ShellCheck/ASTLib.hs Normal file
View File

@@ -0,0 +1,492 @@
{-
Copyright 2012-2015 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/>.
-}
module ShellCheck.ASTLib where
import ShellCheck.AST
import Control.Monad.Writer
import Control.Monad
import Data.Char
import Data.Functor
import Data.List
import Data.Maybe
-- 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_NormalWord _ l -> any willSplit l
_ -> False
isGlob T_Extglob {} = True
isGlob T_Glob {} = True
isGlob (T_NormalWord _ l) = any isGlob l
isGlob _ = 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 "Internal shellcheck error, please report! (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 = fromMaybe False $ do
str <- getLeadingUnquotedString token
return $ "-" `isPrefixOf` str
-- Given a T_DollarBraced, return a simplified version of the string contents.
bracedString (T_DollarBraced _ l) = concat $ oversimplify l
bracedString _ = error "Internal shellcheck error, please report! (bracedString on non-variable)"
-- Is this an expansion of multiple items of an array?
isArrayExpansion t@(T_DollarBraced _ _) =
let string = bracedString t in
"@" `isPrefixOf` string ||
not ("#" `isPrefixOf` string) && "[@]" `isInfixOf` string
isArrayExpansion _ = False
-- Is it possible that this arg becomes multiple args?
mayBecomeMultipleArgs t = willBecomeMultipleArgs t || f t
where
f t@(T_DollarBraced _ _) =
let string = bracedString t in
"!" `isPrefixOf` string
f (T_DoubleQuoted _ parts) = any f parts
f (T_NormalWord _ parts) = any f 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_DoubleQuoted _ parts) = any f parts
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, skipping over all non-literals
onlyLiteralString :: Token -> String
onlyLiteralString = fromJust . getLiteralStringExt (const $ return "")
-- 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
-- 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) : _) -> return s
_ -> Nothing
-- 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
-- Maybe get the literal value of a token, using a custom function
-- to map unrecognized Tokens into strings.
getLiteralStringExt :: (Token -> Maybe String) -> Token -> Maybe 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) ->
if isHexDigit x && isHexDigit y
then chr (16*(digitToInt x) + (digitToInt y)) : rest
else '\\':c:rest
_ | isOctDigit c ->
let digits = take 3 $ takeWhile isOctDigit (c:cs)
num = parseOct digits
in (if num < 256 then chr num else '?') : rest
_ -> '\\' : c : rest
where
rest = decodeEscapes cs
parseOct = f 0
where
f n "" = n
f n (c:rest) = f (n * 8 + digitToInt c) rest
decodeEscapes (c:cs) = c : decodeEscapes cs
decodeEscapes [] = []
-- Is this token a string literal?
isLiteral t = isJust $ getLiteralString t
-- 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
-- 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
getCommandNameAndToken :: Token -> (Maybe String, Token)
getCommandNameAndToken t = fromMaybe (Nothing, t) $ do
(T_SimpleCommand _ _ (w:rest)) <- getCommand t
s <- getLiteralString w
if "busybox" `isSuffixOf` s || "builtin" == s
then
case rest of
(applet:_) -> return (getLiteralString applet, applet)
_ -> return (Just s, w)
else
return (Just s, w)
-- 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
where
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
isBraceExpansion t = case t of T_BraceExpansion {} -> True; _ -> False
-- Get the lists of commands from tokens that contain them, such as
-- the body 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 _ _ cmds -> [cmds]
T_UntilExpression _ _ cmds -> [cmds]
T_ForIn _ _ _ cmds -> [cmds]
T_ForArithmetic _ _ _ _ cmds -> [cmds]
T_IfExpression _ thens elses -> map snd thens ++ [elses]
T_Annotation _ _ t -> getCommandSequences t
_ -> []
-- Get a list of names of associative arrays
getAssociativeArrays t =
nub . execWriter $ doAnalysis f t
where
f :: Token -> Writer [String] ()
f t@T_SimpleCommand {} = fromMaybe (return ()) $ do
name <- getCommandName t
let assocNames = ["declare","local","typeset"]
guard $ elem name assocNames
let flags = getAllFlags t
guard $ elem "A" $ map snd flags
let args = map fst . filter ((==) "" . snd) $ 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 -> Maybe [PseudoGlob]
wordToPseudoGlob word =
simplifyPseudoGlob . concat <$> mapM f (getWordParts word)
where
f x = case x of
T_Literal _ s -> return $ map PGChar s
T_SingleQuoted _ s -> return $ map PGChar s
T_DollarBraced {} -> return [PGMany]
T_DollarExpansion {} -> return [PGMany]
T_Backticked {} -> return [PGMany]
T_Glob _ "?" -> return [PGAny]
T_Glob _ ('[':_) -> return [PGAny]
T_Glob {} -> return [PGMany]
T_Extglob {} -> return [PGMany]
_ -> return [PGMany]
-- Turn a word into a PG pattern, but only if we can preserve
-- exact semantics.
wordToExactPseudoGlob :: Token -> Maybe [PseudoGlob]
wordToExactPseudoGlob word =
simplifyPseudoGlob . concat <$> mapM f (getWordParts word)
where
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]
_ -> fail "Unknown token type"
-- 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 = fromMaybe True $
liftM2 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_DollarExpansion {} -> True
T_DollarBraceCommandExpansion {} -> True
T_Backticked {} -> True
T_DollarBraced {} -> True
_ -> False

3185
src/ShellCheck/Analytics.hs Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,45 @@
{-
Copyright 2012-2015 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/>.
-}
module ShellCheck.Analyzer (analyzeScript) where
import ShellCheck.Analytics
import ShellCheck.AnalyzerLib
import ShellCheck.Interface
import Data.List
import Data.Monoid
import qualified ShellCheck.Checks.Commands
import qualified ShellCheck.Checks.ShellSupport
-- TODO: Clean up the cruft this is layered on
analyzeScript :: AnalysisSpec -> AnalysisResult
analyzeScript spec = newAnalysisResult {
arComments =
filterByAnnotation spec params . nub $
runAnalytics spec
++ runChecker params (checkers params)
}
where
params = makeParameters spec
checkers params = mconcat $ map ($ params) [
ShellCheck.Checks.Commands.checker,
ShellCheck.Checks.ShellSupport.checker
]

View File

@@ -0,0 +1,932 @@
{-
Copyright 2012-2015 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 FlexibleContexts #-}
module ShellCheck.AnalyzerLib where
import ShellCheck.AST
import ShellCheck.ASTLib
import ShellCheck.Data
import ShellCheck.Interface
import ShellCheck.Parser
import ShellCheck.Regex
import Control.Arrow (first)
import Control.DeepSeq
import Control.Monad.Identity
import Control.Monad.RWS
import Control.Monad.State
import Control.Monad.Writer
import Data.Char
import Data.List
import qualified Data.Map as Map
import Data.Maybe
import Data.Semigroup
prop :: Bool -> IO ()
prop False = putStrLn "FAIL"
prop True = return ()
type Analysis = AnalyzerM ()
type AnalyzerM a = RWS Parameters [TokenComment] Cache a
nullCheck = const $ return ()
data Checker = Checker {
perScript :: Root -> Analysis,
perToken :: Token -> Analysis
}
runChecker :: Parameters -> Checker -> [TokenComment]
runChecker params checker = notes
where
root = rootNode params
check = perScript checker `composeAnalyzers` (\(Root x) -> void $ doAnalysis (perToken checker) x)
notes = snd $ evalRWS (check $ Root root) params Cache
instance Semigroup Checker where
(<>) x y = Checker {
perScript = perScript x `composeAnalyzers` perScript y,
perToken = perToken x `composeAnalyzers` perToken y
}
instance Monoid Checker where
mempty = Checker {
perScript = nullCheck,
perToken = nullCheck
}
mappend = (Data.Semigroup.<>)
composeAnalyzers :: (a -> Analysis) -> (a -> Analysis) -> a -> Analysis
composeAnalyzers f g x = f x >> g x
data Parameters = Parameters {
hasLastpipe :: Bool, -- Whether this script has the 'lastpipe' option set/default.
hasSetE :: Bool, -- Whether this script has 'set -e' anywhere.
variableFlow :: [StackData], -- A linear (bad) analysis of data flow
parentMap :: Map.Map Id Token, -- A map from Id to parent Token
shellType :: Shell, -- The shell type, such as Bash or Ksh
shellTypeSpecified :: Bool, -- True if shell type was forced via flags
rootNode :: Token, -- The root node of the AST
tokenPositions :: Map.Map Id (Position, Position) -- map from token id to start and end position
} deriving (Show)
-- TODO: Cache results of common AST ops here
data Cache = Cache {}
data Scope = SubshellScope String | NoneScope deriving (Show, Eq)
data StackData =
StackScope Scope
| StackScopeEnd
-- (Base expression, specific position, var name, assigned values)
| Assignment (Token, Token, String, DataType)
| Reference (Token, Token, String)
deriving (Show)
data DataType = DataString DataSource | DataArray DataSource
deriving (Show)
data DataSource =
SourceFrom [Token]
| SourceExternal
| SourceDeclaration
| SourceInteger
| SourceChecked
deriving (Show)
data VariableState = Dead Token String | Alive deriving (Show)
defaultSpec pr = spec {
asShellType = Nothing,
asCheckSourced = False,
asExecutionMode = Executed,
asTokenPositions = prTokenPositions pr
} where spec = newAnalysisSpec (fromJust $ prRoot pr)
pScript s =
let
pSpec = newParseSpec {
psFilename = "script",
psScript = s
}
in runIdentity $ parseScript (mockedSystemInterface []) pSpec
-- For testing. If parsed, returns whether there are any comments
producesComments :: Checker -> String -> Maybe Bool
producesComments c s = do
let pr = pScript s
prRoot pr
let spec = defaultSpec pr
let params = makeParameters spec
return . not . null $ runChecker params c
makeComment :: Severity -> Id -> Code -> String -> TokenComment
makeComment severity id code note =
newTokenComment {
tcId = id,
tcComment = newComment {
cSeverity = severity,
cCode = code,
cMessage = note
}
}
addComment note = note `deepseq` tell [note]
warn :: MonadWriter [TokenComment] m => Id -> Code -> String -> m ()
warn id code str = addComment $ makeComment WarningC id code str
err id code str = addComment $ makeComment ErrorC id code str
info id code str = addComment $ makeComment InfoC id code str
style id code str = addComment $ makeComment StyleC id code str
warnWithFix id code str fix = addComment $
let comment = makeComment WarningC id code str in
comment {
tcFix = Just fix
}
makeCommentWithFix :: Severity -> Id -> Code -> String -> Fix -> TokenComment
makeCommentWithFix severity id code str fix =
let comment = makeComment severity id code str
withFix = comment {
tcFix = Just fix
}
in withFix `deepseq` withFix
makeParameters spec =
let params = Parameters {
rootNode = root,
shellType = fromMaybe (determineShell root) $ asShellType spec,
hasSetE = containsSetE root,
hasLastpipe =
case shellType params of
Bash -> containsLastpipe root
Dash -> False
Sh -> False
Ksh -> True,
shellTypeSpecified = isJust $ asShellType spec,
parentMap = getParentTree root,
variableFlow = getVariableFlow params root,
tokenPositions = asTokenPositions spec
} in params
where root = asScript spec
-- Does this script mention 'set -e' anywhere?
-- Used as a hack to disable certain warnings.
containsSetE root = isNothing $ doAnalysis (guard . not . isSetE) root
where
isSetE t =
case t of
T_Script _ str _ -> str `matches` re
T_SimpleCommand {} ->
t `isUnqualifiedCommand` "set" &&
("errexit" `elem` oversimplify t ||
"e" `elem` map snd (getAllFlags t))
_ -> False
re = mkRegex "[[:space:]]-[^-]*e"
-- Does this script mention 'shopt -s lastpipe' anywhere?
-- Also used as a hack.
containsLastpipe root =
isNothing $ doAnalysis (guard . not . isShoptLastPipe) root
where
isShoptLastPipe t =
case t of
T_SimpleCommand {} ->
t `isUnqualifiedCommand` "shopt" &&
("lastpipe" `elem` oversimplify t)
_ -> False
-- |
-- >>> prop $ determineShellTest "#!/bin/sh" == Sh
-- >>> prop $ determineShellTest "#!/usr/bin/env ksh" == Ksh
-- >>> prop $ determineShellTest "" == Bash
-- >>> prop $ determineShellTest "#!/bin/sh -e" == Sh
-- >>> prop $ determineShellTest "#!/bin/ksh\n#shellcheck shell=sh\nfoo" == Sh
-- >>> prop $ determineShellTest "#shellcheck shell=sh\nfoo" == Sh
-- >>> prop $ determineShellTest "#! /bin/sh" == Sh
-- >>> prop $ determineShellTest "#! /bin/ash" == Dash
determineShellTest = determineShell . fromJust . prRoot . pScript
determineShell t = fromMaybe Bash $ do
shellString <- foldl mplus Nothing $ getCandidates t
shellForExecutable shellString
where
forAnnotation t =
case t of
(ShellOverride s) -> return s
_ -> fail ""
getCandidates :: Token -> [Maybe String]
getCandidates t@T_Script {} = [Just $ fromShebang t]
getCandidates (T_Annotation _ annotations s) =
map forAnnotation annotations ++
[Just $ fromShebang s]
fromShebang (T_Script _ s t) = executableFromShebang s
-- Given a string like "/bin/bash" or "/usr/bin/env dash",
-- return the shell basename like "bash" or "dash"
executableFromShebang :: String -> String
executableFromShebang = shellFor
where
shellFor s | "/env " `isInfixOf` s = head (drop 1 (words s)++[""])
shellFor s | ' ' `elem` s = shellFor $ takeWhile (/= ' ') s
shellFor s = reverse . takeWhile (/= '/') . reverse $ s
-- Given a root node, make a map from Id to parent Token.
-- This is used to populate parentMap in Parameters
getParentTree :: Token -> Map.Map Id Token
getParentTree t =
snd . snd $ runState (doStackAnalysis pre post t) ([], Map.empty)
where
pre t = modify (first ((:) t))
post t = do
(x, map) <- get
case x of
_:rest -> case rest of [] -> put (rest, map)
(x:_) -> put (rest, Map.insert (getId t) x map)
-- Given a root node, make a map from Id to Token
getTokenMap :: Token -> Map.Map Id Token
getTokenMap t =
execState (doAnalysis f t) Map.empty
where
f t = modify (Map.insert (getId t) t)
-- Is this token in a quoting free context? (i.e. would variable expansion split)
-- True: Assignments, [[ .. ]], here docs, already in double quotes
-- False: Regular words
isStrictlyQuoteFree = isQuoteFreeNode True
-- Like above, but also allow some cases where splitting may be desired.
-- True: Like above + for loops
-- False: Like above
isQuoteFree = isQuoteFreeNode False
isQuoteFreeNode strict tree t =
(isQuoteFreeElement t == Just True) ||
head (mapMaybe isQuoteFreeContext (drop 1 $ getPath tree t) ++ [False])
where
-- Is this node self-quoting in itself?
isQuoteFreeElement t =
case t of
T_Assignment {} -> return True
T_FdRedirect {} -> return True
_ -> Nothing
-- Are any subnodes inherently self-quoting?
isQuoteFreeContext t =
case t of
TC_Nullary _ DoubleBracket _ -> return True
TC_Unary _ DoubleBracket _ _ -> return True
TC_Binary _ DoubleBracket _ _ _ -> return True
TA_Sequence {} -> return True
T_Arithmetic {} -> return True
T_Assignment {} -> return True
T_Redirecting {} -> return False
T_DoubleQuoted _ _ -> return True
T_DollarDoubleQuoted _ _ -> return True
T_CaseExpression {} -> return True
T_HereDoc {} -> return True
T_DollarBraced {} -> return True
-- When non-strict, pragmatically assume it's desirable to split here
T_ForIn {} -> return (not strict)
T_SelectIn {} -> return (not strict)
_ -> Nothing
-- Check if a token is a parameter to a certain command by name:
-- Example: isParamTo (parentMap params) "sed" t
isParamTo :: Map.Map Id Token -> String -> Token -> Bool
isParamTo tree cmd =
go
where
go x = case Map.lookup (getId x) tree of
Nothing -> False
Just parent -> check parent
check t =
case t of
T_SingleQuoted _ _ -> go t
T_DoubleQuoted _ _ -> go t
T_NormalWord _ _ -> go t
T_SimpleCommand {} -> isCommand t cmd
T_Redirecting {} -> isCommand t cmd
_ -> False
-- Get the parent command (T_Redirecting) of a Token, if any.
getClosestCommand :: Map.Map Id Token -> Token -> Maybe Token
getClosestCommand tree t =
findFirst findCommand $ getPath tree t
where
findCommand t =
case t of
T_Redirecting {} -> return True
T_Script {} -> return False
_ -> Nothing
-- Like above, if koala_man knew Haskell when starting this project.
getClosestCommandM t = do
tree <- asks parentMap
return $ getClosestCommand tree t
-- Is the token used as a command name (the first word in a T_SimpleCommand)?
usedAsCommandName tree token = go (getId token) (tail $ getPath tree token)
where
go currentId (T_NormalWord id [word]:rest)
| currentId == getId word = go id rest
go currentId (T_DoubleQuoted id [word]:rest)
| currentId == getId word = go id rest
go currentId (T_SimpleCommand _ _ (word:_):_)
| currentId == getId word = True
go _ _ = False
-- A list of the element and all its parents up to the root node.
getPath tree t = t :
case Map.lookup (getId t) tree of
Nothing -> []
Just parent -> getPath tree parent
-- Version of the above taking the map from the current context
-- Todo: give this the name "getPath"
getPathM t = do
map <- asks parentMap
return $ getPath map t
isParentOf tree parent child =
elem (getId parent) . map getId $ getPath tree child
parents params = getPath (parentMap params)
pathTo t = do
parents <- reader parentMap
return $ getPath parents t
-- Find the first match in a list where the predicate is Just True.
-- Stops if it's Just False and ignores Nothing.
findFirst :: (a -> Maybe Bool) -> [a] -> Maybe a
findFirst p l =
case l of
[] -> Nothing
(x:xs) ->
case p x of
Just True -> return x
Just False -> Nothing
Nothing -> findFirst p xs
-- Check whether a word is entirely output from a single command
tokenIsJustCommandOutput t = case t of
T_NormalWord id [T_DollarExpansion _ cmds] -> check cmds
T_NormalWord id [T_DoubleQuoted _ [T_DollarExpansion _ cmds]] -> check cmds
T_NormalWord id [T_Backticked _ cmds] -> check cmds
T_NormalWord id [T_DoubleQuoted _ [T_Backticked _ cmds]] -> check cmds
_ -> False
where
check [x] = not $ isOnlyRedirection x
check _ = False
-- TODO: Replace this with a proper Control Flow Graph
getVariableFlow params t =
let (_, stack) = runState (doStackAnalysis startScope endScope t) []
in reverse stack
where
startScope t =
let scopeType = leadType params t
in do
when (scopeType /= NoneScope) $ modify (StackScope scopeType:)
when (assignFirst t) $ setWritten t
endScope t =
let scopeType = leadType params t
in do
setRead t
unless (assignFirst t) $ setWritten t
when (scopeType /= NoneScope) $ modify (StackScopeEnd:)
assignFirst T_ForIn {} = True
assignFirst T_SelectIn {} = True
assignFirst _ = False
setRead t =
let read = getReferencedVariables (parentMap params) t
in mapM_ (\v -> modify (Reference v:)) read
setWritten t =
let written = getModifiedVariables t
in mapM_ (\v -> modify (Assignment v:)) written
leadType params t =
case t of
T_DollarExpansion _ _ -> SubshellScope "$(..) expansion"
T_Backticked _ _ -> SubshellScope "`..` expansion"
T_Backgrounded _ _ -> SubshellScope "backgrounding &"
T_Subshell _ _ -> SubshellScope "(..) group"
T_CoProcBody _ _ -> SubshellScope "coproc"
T_Redirecting {} ->
if fromMaybe False causesSubshell
then SubshellScope "pipeline"
else NoneScope
_ -> NoneScope
where
parentPipeline = do
parent <- Map.lookup (getId t) (parentMap params)
case parent of
T_Pipeline {} -> return parent
_ -> Nothing
causesSubshell = do
(T_Pipeline _ _ list) <- parentPipeline
if length list <= 1
then return False
else if not $ hasLastpipe params
then return True
else return . not $ (getId . head $ reverse list) == getId t
getModifiedVariables t =
case t of
T_SimpleCommand _ vars [] ->
concatMap (\x -> case x of
T_Assignment id _ name _ w ->
[(x, x, name, dataTypeFrom DataString w)]
_ -> []
) vars
c@T_SimpleCommand {} ->
getModifiedVariableCommand c
TA_Unary _ "++|" v@(TA_Variable _ name _) ->
[(t, v, name, DataString $ SourceFrom [v])]
TA_Unary _ "|++" v@(TA_Variable _ name _) ->
[(t, v, name, DataString $ SourceFrom [v])]
TA_Assignment _ op (TA_Variable _ name _) rhs -> maybeToList $ do
guard $ op `elem` ["=", "*=", "/=", "%=", "+=", "-=", "<<=", ">>=", "&=", "^=", "|="]
return (t, t, name, DataString $ SourceFrom [rhs])
-- Count [[ -v foo ]] as an "assignment".
-- This is to prevent [ -v foo ] being unassigned or unused.
TC_Unary id _ "-v" token -> maybeToList $ do
str <- fmap (takeWhile (/= '[')) $ -- Quoted index
flip getLiteralStringExt token $ \x ->
case x of
T_Glob _ s -> return s -- Unquoted index
_ -> Nothing
guard . not . null $ str
return (t, token, str, DataString SourceChecked)
T_DollarBraced _ l -> maybeToList $ do
let string = bracedString t
let modifier = getBracedModifier string
guard $ ":=" `isPrefixOf` modifier
return (t, t, getBracedReference string, DataString $ SourceFrom [l])
t@(T_FdRedirect _ ('{':var) op) -> -- {foo}>&2 modifies foo
[(t, t, takeWhile (/= '}') var, DataString SourceInteger) | not $ isClosingFileOp op]
t@(T_CoProc _ name _) ->
[(t, t, fromMaybe "COPROC" name, DataArray SourceInteger)]
--Points to 'for' rather than variable
T_ForIn id str [] _ -> [(t, t, str, DataString SourceExternal)]
T_ForIn id str words _ -> [(t, t, str, DataString $ SourceFrom words)]
T_SelectIn id str words _ -> [(t, t, str, DataString $ SourceFrom words)]
_ -> []
isClosingFileOp op =
case op of
T_IoDuplicate _ (T_GREATAND _) "-" -> True
T_IoDuplicate _ (T_LESSAND _) "-" -> True
_ -> False
-- Consider 'export/declare -x' a reference, since it makes the var available
getReferencedVariableCommand base@(T_SimpleCommand _ _ (T_NormalWord _ (T_Literal _ x:_):rest)) =
case x of
"export" -> if "f" `elem` flags
then []
else concatMap getReference rest
"declare" -> if
any (`elem` flags) ["x", "p"] &&
(not $ any (`elem` flags) ["f", "F"])
then concatMap getReference rest
else []
"readonly" ->
if any (`elem` flags) ["f", "p"]
then []
else concatMap getReference rest
"trap" ->
case rest of
head:_ -> map (\x -> (head, head, x)) $ getVariablesFromLiteralToken head
_ -> []
_ -> []
where
getReference t@(T_Assignment _ _ name _ value) = [(t, t, name)]
getReference t@(T_NormalWord _ [T_Literal _ name]) | not ("-" `isPrefixOf` name) = [(t, t, name)]
getReference _ = []
flags = map snd $ getAllFlags base
getReferencedVariableCommand _ = []
-- The function returns a tuple consisting of four items describing an assignment.
-- Given e.g. declare foo=bar
-- (
-- BaseCommand :: Token, -- The command/structure assigning the variable, i.e. declare foo=bar
-- AssignmentToken :: Token, -- The specific part that assigns this variable, i.e. foo=bar
-- VariableName :: String, -- The variable name, i.e. foo
-- VariableValue :: DataType -- A description of the value being assigned, i.e. "Literal string with value foo"
-- )
getModifiedVariableCommand base@(T_SimpleCommand _ _ (T_NormalWord _ (T_Literal _ x:_):rest)) =
filter (\(_,_,s,_) -> not ("-" `isPrefixOf` s)) $
case x of
"read" ->
let params = map getLiteral rest
readArrayVars = getReadArrayVariables rest
in
catMaybes . (++ readArrayVars) . takeWhile isJust . reverse $ params
"getopts" ->
case rest of
opts:var:_ -> maybeToList $ getLiteral var
_ -> []
"let" -> concatMap letParamToLiteral rest
"export" ->
if "f" `elem` flags then [] else concatMap getModifierParamString rest
"declare" -> if any (`elem` flags) ["F", "f", "p"] then [] else declaredVars
"typeset" -> declaredVars
"local" -> concatMap getModifierParamString rest
"readonly" ->
if any (`elem` flags) ["f", "p"]
then []
else concatMap getModifierParamString rest
"set" -> maybeToList $ do
params <- getSetParams rest
return (base, base, "@", DataString $ SourceFrom params)
"printf" -> maybeToList $ getPrintfVariable rest
"mapfile" -> maybeToList $ getMapfileArray base rest
"readarray" -> maybeToList $ getMapfileArray base rest
_ -> []
where
flags = map snd $ getAllFlags base
stripEquals s = let rest = dropWhile (/= '=') s in
if rest == "" then "" else tail rest
stripEqualsFrom (T_NormalWord id1 (T_Literal id2 s:rs)) =
T_NormalWord id1 (T_Literal id2 (stripEquals s):rs)
stripEqualsFrom (T_NormalWord id1 [T_DoubleQuoted id2 [T_Literal id3 s]]) =
T_NormalWord id1 [T_DoubleQuoted id2 [T_Literal id3 (stripEquals s)]]
stripEqualsFrom t = t
declaredVars = concatMap (getModifierParam defaultType) rest
where
defaultType = if any (`elem` flags) ["a", "A"] then DataArray else DataString
getLiteralOfDataType t d = do
s <- getLiteralString t
when ("-" `isPrefixOf` s) $ fail "argument"
return (base, t, s, d)
getLiteral t = getLiteralOfDataType t (DataString SourceExternal)
getLiteralArray t = getLiteralOfDataType t (DataArray SourceExternal)
getModifierParamString = getModifierParam DataString
getModifierParam def t@(T_Assignment _ _ name _ value) =
[(base, t, name, dataTypeFrom def value)]
getModifierParam def t@T_NormalWord {} = maybeToList $ do
name <- getLiteralString t
guard $ isVariableName name
return (base, t, name, def SourceDeclaration)
getModifierParam _ _ = []
letParamToLiteral token =
if var == ""
then []
else [(base, token, var, DataString $ SourceFrom [stripEqualsFrom token])]
where var = takeWhile isVariableChar $ dropWhile (`elem` "+-") $ concat $ oversimplify token
getSetParams (t:_:rest) | getLiteralString t == Just "-o" = getSetParams rest
getSetParams (t:rest) =
let s = getLiteralString t in
case s of
Just "--" -> return rest
Just ('-':_) -> getSetParams rest
_ -> return (t:fromMaybe [] (getSetParams rest))
getSetParams [] = Nothing
getPrintfVariable list = f $ map (\x -> (x, getLiteralString x)) list
where
f ((_, Just "-v") : (t, Just var) : _) = return (base, t, var, DataString $ SourceFrom list)
f (_:rest) = f rest
f [] = fail "not found"
-- mapfile has some curious syntax allowing flags plus 0..n variable names
-- where only the first non-option one is used if any. Here we cheat and
-- just get the last one, if it's a variable name.
getMapfileArray base arguments = do
lastArg <- listToMaybe (reverse arguments)
name <- getLiteralString lastArg
guard $ isVariableName name
return (base, lastArg, name, DataArray SourceExternal)
-- get all the array variables used in read, e.g. read -a arr
getReadArrayVariables args = do
map (getLiteralArray . snd)
(filter (\(x,_) -> getLiteralString x == Just "-a") (zip (args) (tail args)))
getModifiedVariableCommand _ = []
getIndexReferences s = fromMaybe [] $ do
match <- matchRegex re s
index <- match !!! 0
return $ matchAllStrings variableNameRegex index
where
re = mkRegex "(\\[.*\\])"
-- |
-- >>> prop $ getOffsetReferences ":bar" == ["bar"]
-- >>> prop $ getOffsetReferences ":bar:baz" == ["bar", "baz"]
-- >>> prop $ getOffsetReferences "[foo]:bar" == ["bar"]
-- >>> prop $ getOffsetReferences "[foo]:bar:baz" == ["bar", "baz"]
getOffsetReferences mods = fromMaybe [] $ do
-- if mods start with [, then drop until ]
match <- matchRegex re mods
offsets <- match !!! 1
return $ matchAllStrings variableNameRegex offsets
where
re = mkRegex "^(\\[.+\\])? *:([^-=?+].*)"
getReferencedVariables parents t =
case t of
T_DollarBraced id l -> let str = bracedString t in
(t, t, getBracedReference str) :
map (\x -> (l, l, x)) (
getIndexReferences str
++ getOffsetReferences (getBracedModifier str))
TA_Variable id name _ ->
if isArithmeticAssignment t
then []
else [(t, t, name)]
T_Assignment id mode str _ word ->
[(t, t, str) | mode == Append] ++ specialReferences str t word
TC_Unary id _ "-v" token -> getIfReference t token
TC_Unary id _ "-R" token -> getIfReference t token
TC_Binary id DoubleBracket op lhs rhs ->
if isDereferencing op
then concatMap (getIfReference t) [lhs, rhs]
else []
t@(T_FdRedirect _ ('{':var) op) -> -- {foo}>&- references and closes foo
[(t, t, takeWhile (/= '}') var) | isClosingFileOp op]
x -> getReferencedVariableCommand x
where
-- Try to reduce false positives for unused vars only referenced from evaluated vars
specialReferences name base word =
if name `elem` [
"PS1", "PS2", "PS3", "PS4",
"PROMPT_COMMAND"
]
then
map (\x -> (base, base, x)) $
getVariablesFromLiteralToken word
else []
literalizer t = case t of
T_Glob _ s -> return s -- Also when parsed as globs
_ -> Nothing
getIfReference context token = maybeToList $ do
str <- getLiteralStringExt literalizer token
guard . not $ null str
when (isDigit $ head str) $ fail "is a number"
return (context, token, getBracedReference str)
isDereferencing = (`elem` ["-eq", "-ne", "-lt", "-le", "-gt", "-ge"])
isArithmeticAssignment t = case getPath parents t of
this: TA_Assignment _ "=" lhs _ :_ -> lhs == t
_ -> False
dataTypeFrom defaultType v = (case v of T_Array {} -> DataArray; _ -> defaultType) $ SourceFrom [v]
--- Command specific checks
-- Compare a command to a string: t `isCommand` "sed" (also matches /usr/bin/sed)
isCommand token str = isCommandMatch token (\cmd -> cmd == str || ('/' : str) `isSuffixOf` cmd)
-- Compare a command to a literal. Like above, but checks full path.
isUnqualifiedCommand token str = isCommandMatch token (== str)
isCommandMatch token matcher = fromMaybe False $
fmap matcher (getCommandName token)
-- |
-- Does this regex look like it was intended as a glob?
--
-- >>> isConfusedGlobRegex "*foo*"
-- True
--
-- >>> isConfusedGlobRegex ".*foo.*"
-- False
--
isConfusedGlobRegex :: String -> Bool
isConfusedGlobRegex ('*':_) = True
isConfusedGlobRegex [x,'*'] | x /= '\\' = True
isConfusedGlobRegex _ = False
isVariableStartChar x = x == '_' || isAsciiLower x || isAsciiUpper x
isVariableChar x = isVariableStartChar x || isDigit x
variableNameRegex = mkRegex "[_a-zA-Z][_a-zA-Z0-9]*"
-- |
-- >>> prop $ isVariableName "_fo123"
-- >>> prop $ not $ isVariableName "4"
-- >>> prop $ not $ isVariableName "test: "
isVariableName (x:r) = isVariableStartChar x && all isVariableChar r
isVariableName _ = False
getVariablesFromLiteralToken token =
getVariablesFromLiteral (fromJust $ getLiteralStringExt (const $ return " ") token)
-- Try to get referenced variables from a literal string like "$foo"
-- Ignores tons of cases like arithmetic evaluation and array indices.
-- >>> prop $ getVariablesFromLiteral "$foo${bar//a/b}$BAZ" == ["foo", "bar", "BAZ"]
getVariablesFromLiteral string =
map (!! 0) $ matchAllSubgroups variableRegex string
where
variableRegex = mkRegex "\\$\\{?([A-Za-z0-9_]+)"
-- |
-- Get the variable name from an expansion like ${var:-foo}
--
-- >>> prop $ getBracedReference "foo" == "foo"
-- >>> prop $ getBracedReference "#foo" == "foo"
-- >>> prop $ getBracedReference "#" == "#"
-- >>> prop $ getBracedReference "##" == "#"
-- >>> prop $ getBracedReference "#!" == "!"
-- >>> prop $ getBracedReference "!#" == "#"
-- >>> prop $ getBracedReference "!foo#?" == "foo"
-- >>> prop $ getBracedReference "foo-bar" == "foo"
-- >>> prop $ getBracedReference "foo:-bar" == "foo"
-- >>> prop $ getBracedReference "foo: -1" == "foo"
-- >>> prop $ getBracedReference "!os*" == ""
-- >>> prop $ getBracedReference "!os?bar**" == ""
-- >>> prop $ getBracedReference "foo[bar]" == "foo"
getBracedReference s = fromMaybe s $
nameExpansion s `mplus` takeName noPrefix `mplus` getSpecial noPrefix `mplus` getSpecial s
where
noPrefix = dropPrefix s
dropPrefix (c:rest) = if c `elem` "!#" then rest else c:rest
dropPrefix "" = ""
takeName s = do
let name = takeWhile isVariableChar s
guard . not $ null name
return name
getSpecial (c:_) =
if c `elem` "*@#?-$!" then return [c] else fail "not special"
getSpecial _ = fail "empty"
nameExpansion ('!':rest) = do -- e.g. ${!foo*bar*}
let suffix = dropWhile isVariableChar rest
guard $ suffix /= rest -- e.g. ${!@}
first <- suffix !!! 0
guard $ first `elem` "*?"
return ""
nameExpansion _ = Nothing
-- |
-- >>> prop $ getBracedModifier "foo:bar:baz" == ":bar:baz"
-- >>> prop $ getBracedModifier "!var:-foo" == ":-foo"
-- >>> prop $ getBracedModifier "foo[bar]" == "[bar]"
getBracedModifier s = fromMaybe "" . listToMaybe $ do
let var = getBracedReference s
a <- dropModifier s
dropPrefix var a
where
dropPrefix [] t = return t
dropPrefix (a:b) (c:d) | a == c = dropPrefix b d
dropPrefix _ _ = []
dropModifier (c:rest) | c `elem` "#!" = [rest, c:rest]
dropModifier x = [x]
-- Useful generic functions.
-- Run an action in a Maybe (or do nothing).
-- Example:
--
-- @
-- potentially $ do
-- s <- getLiteralString cmd
-- guard $ s `elem` ["--recursive", "-r"]
-- return $ warn .. "Something something recursive"
-- @
potentially :: Monad m => Maybe (m ()) -> m ()
potentially = fromMaybe (return ())
-- Get element 0 or a default. Like `head` but safe.
headOrDefault _ (a:_) = a
headOrDefault def _ = def
--- Get element n of a list, or Nothing. Like `!!` but safe.
(!!!) list i =
case drop i list of
[] -> Nothing
(r:_) -> Just r
-- Run a command if the shell is in the given list
whenShell l c = do
shell <- asks shellType
when (shell `elem` l ) c
filterByAnnotation asSpec params =
filter (not . shouldIgnore)
where
token = asScript asSpec
shouldIgnore note =
any (shouldIgnoreFor (getCode note)) $
getPath parents (T_Bang $ tcId note)
shouldIgnoreFor num (T_Annotation _ anns _) =
any hasNum anns
where
hasNum (DisableComment ts) = num == ts
hasNum _ = False
shouldIgnoreFor _ T_Include {} = not $ asCheckSourced asSpec
shouldIgnoreFor _ _ = False
parents = parentMap params
getCode = cCode . tcComment
-- Is this a ${#anything}, to get string length or array count?
isCountingReference (T_DollarBraced id token) =
case concat $ oversimplify token of
'#':_ -> True
_ -> False
isCountingReference _ = False
-- FIXME: doesn't handle ${a:+$var} vs ${a:+"$var"}
isQuotedAlternativeReference t =
case t of
T_DollarBraced _ _ ->
getBracedModifier (bracedString t) `matches` re
_ -> False
where
re = mkRegex "(^|\\]):?\\+"
-- getGnuOpts "erd:u:" will parse a SimpleCommand like
-- read -re -d : -u 3 bar
-- into
-- Just [("r", -re), ("e", -re), ("d", :), ("u", 3), ("", bar)]
-- where flags with arguments map to arguments, while others map to themselves.
-- Any unrecognized flag will result in Nothing.
getGnuOpts = getOpts getAllFlags
getBsdOpts = getOpts getLeadingFlags
getOpts :: (Token -> [(Token, String)]) -> String -> Token -> Maybe [(String, Token)]
getOpts flagTokenizer string cmd = process flags
where
flags = flagTokenizer cmd
flagList (c:':':rest) = ([c], True) : flagList rest
flagList (c:rest) = ([c], False) : flagList rest
flagList [] = []
flagMap = Map.fromList $ ("", False) : flagList string
process [] = return []
process [(token, flag)] = do
takesArg <- Map.lookup flag flagMap
guard $ not takesArg
return [(flag, token)]
process ((token1, flag1):rest2@((token2, flag2):rest)) = do
takesArg <- Map.lookup flag1 flagMap
if takesArg
then do
guard $ flag2 == ""
more <- process rest
return $ (flag1, token2) : more
else do
more <- process rest2
return $ (flag1, token1) : more

253
src/ShellCheck/Checker.hs Normal file
View File

@@ -0,0 +1,253 @@
{-
Copyright 2012-2015 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/>.
-}
module ShellCheck.Checker (checkScript) where
import ShellCheck.Interface
import ShellCheck.Parser
import ShellCheck.Analyzer
import Data.Either
import Data.Functor
import Data.List
import Data.Maybe
import Data.Ord
import Control.Monad.Identity
import qualified Data.Map as Map
import qualified System.IO
import Prelude hiding (readFile)
import Control.Monad
tokenToPosition startMap t = fromMaybe fail $ do
span <- Map.lookup (tcId t) startMap
return $ newPositionedComment {
pcStartPos = fst span,
pcEndPos = snd span,
pcComment = tcComment t,
pcFix = tcFix t
}
where
fail = error "Internal shellcheck error: id doesn't exist. Please report!"
checkScript :: Monad m => SystemInterface m -> CheckSpec -> m CheckResult
checkScript sys spec = do
results <- checkScript (csScript spec)
return emptyCheckResult {
crFilename = csFilename spec,
crComments = results
}
where
checkScript contents = do
result <- parseScript sys newParseSpec {
psFilename = csFilename spec,
psScript = contents,
psCheckSourced = csCheckSourced spec,
psShellTypeOverride = csShellTypeOverride spec
}
let parseMessages = prComments result
let tokenPositions = prTokenPositions result
let analysisSpec root =
as {
asScript = root,
asShellType = csShellTypeOverride spec,
asCheckSourced = csCheckSourced spec,
asExecutionMode = Executed,
asTokenPositions = tokenPositions
} where as = newAnalysisSpec root
let analysisMessages =
fromMaybe [] $
(arComments . analyzeScript . analysisSpec)
<$> prRoot result
let translator = tokenToPosition tokenPositions
return . nub . sortMessages . filter shouldInclude $
(parseMessages ++ map translator analysisMessages)
shouldInclude pc =
let code = cCode (pcComment pc)
severity = cSeverity (pcComment pc)
in
code `notElem` csExcludedWarnings spec &&
severity <= csMinSeverity spec
sortMessages = sortBy (comparing order)
order pc =
let pos = pcStartPos pc
comment = pcComment pc in
(posFile pos,
posLine pos,
posColumn pos,
cSeverity comment,
cCode comment,
cMessage comment)
getPosition = pcStartPos
getErrors sys spec =
sort . map getCode . crComments $
runIdentity (checkScript sys spec)
where
getCode = cCode . pcComment
check = checkWithIncludes []
checkWithSpec includes =
getErrors (mockedSystemInterface includes)
checkWithIncludes includes src =
checkWithSpec includes emptyCheckSpec {
csScript = src,
csExcludedWarnings = [2148]
}
checkRecursive includes src =
checkWithSpec includes emptyCheckSpec {
csScript = src,
csExcludedWarnings = [2148],
csCheckSourced = True
}
-- | Dummy binding for doctest to run
--
-- >>> check "echo \"$12\""
-- [1037]
--
-- >>> check "#shellcheck disable=SC1037\necho \"$12\""
-- []
--
-- >>> check "#shellcheck disable=SC1037\n#lol\necho \"$12\""
-- []
--
-- >>> check "echo $1"
-- [2086]
--
-- >>> check "#shellcheck disable=SC2086\necho $1"
-- []
--
-- >>> check "#shellcheck disable=SC2086\n#lol\necho $1"
-- []
--
-- >>> :{
-- getErrors
-- (mockedSystemInterface [])
-- emptyCheckSpec {
-- csScript = "echo $1",
-- csExcludedWarnings = [2148, 2086]
-- }
-- :}
-- []
--
-- >>> :{
-- getErrors
-- (mockedSystemInterface [])
-- emptyCheckSpec {
-- csScript = "echo \"$10\"",
-- csExcludedWarnings = [2148, 1037]
-- }
-- :}
-- []
--
-- >>> check "#!/usr/bin/python\ntrue $1\n"
-- [1071]
--
-- >>> :{
-- getErrors
-- (mockedSystemInterface [])
-- emptyCheckSpec {
-- csScript = "#!/usr/bin/python\ntrue\n",
-- csShellTypeOverride = Just Sh
-- }
-- :}
-- []
--
-- >>> check "#!/usr/bin/python\n# shellcheck shell=sh\ntrue\n"
-- []
--
-- >>> check "source /dev/null"
-- []
--
-- >>> check "source lol; echo \"$bar\""
-- [1091,2154]
--
-- >>> checkWithIncludes [("lib", "bar=1")] "source lib; echo \"$bar\""
-- []
--
-- >>> checkWithIncludes [("lib", "bar=1")] ". lib; echo \"$bar\""
-- []
--
-- >>> checkWithIncludes [("lib", "source lib")] "source lib"
-- []
--
-- >>> checkWithIncludes [("lib", "for f; do")] "source lib; echo $1"
-- [1094,2086]
--
-- >>> checkWithIncludes [("lib", "")] ". \"$1\""
-- [1090]
--
-- >>> checkWithIncludes [("lib", "")] "source ~/foo"
-- [1090]
--
-- >>> checkWithIncludes [("lib", "")] "#shellcheck source=lib\n. \"$1\""
-- []
--
-- >>> checkRecursive [("lib", "echo $1")] "source lib"
-- [2086]
--
-- >>> checkRecursive [("lib", "echo \"$10\"")] "source lib"
-- [1037]
--
-- >>> checkWithIncludes [("foo", "source bar"), ("bar", "baz=3")] "#shellcheck source=foo\n. \"$1\"; echo \"$baz\""
-- []
--
-- >>> check "#!/bin/sh\necho $1"
-- [2086]
--
-- >>> check "#!/bin/sh\n# shellcheck disable=2086\necho $1"
-- []
--
-- >>> check "#!/bin/sh\n# shellcheck disable=2086\ntrue\necho $1"
-- []
--
-- >>> check "#!/bin/sh\n#unrelated\n# shellcheck disable=2086\ntrue\necho $1"
-- []
--
-- >>> check "#!/bin/sh\n# shellcheck disable=2086\n#unrelated\ntrue\necho $1"
-- []
--
-- >>> check "#!/bin/sh\n\n\n\n#shellcheck disable=2086\ntrue\necho $1"
-- []
--
-- >>> check "#shellcheck shell=sh\n#unrelated\n#shellcheck disable=2086\ntrue\necho $1"
-- []
--
-- >>> check "#!/bin/sh\n# shellcheck disable=2086\n#unrelated\ntrue\necho $1"
-- []
--
-- check "true\n[ $? == 0 ] && echo $1"
-- [2086, 2181]
--
-- check "# Disable $? warning\n#shellcheck disable=SC2181\n# Disable quoting warning\n#shellcheck disable=2086\ntrue\n[ $? == 0 ] && echo $1"
-- []
--
-- >>> 2039 `elem` checkWithIncludes [("./saywhat.sh", "echo foo")] "#!/bin/sh\nsource ./saywhat.sh"
-- True
--
-- >>> check "fun() {\n# shellcheck disable=SC2188\n> /dev/null\n}\n"
-- []
doctests :: ()
doctests = ()

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,422 @@
{-
Copyright 2012-2016 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 FlexibleContexts #-}
module ShellCheck.Checks.ShellSupport (checker) where
import ShellCheck.AST
import ShellCheck.ASTLib
import ShellCheck.AnalyzerLib
import ShellCheck.Interface
import ShellCheck.Regex
import Control.Monad
import Control.Monad.RWS
import Data.Char
import Data.List
import Data.Maybe
import qualified Data.Map as Map
data ForShell = ForShell [Shell] (Token -> Analysis)
getChecker params list = Checker {
perScript = nullCheck,
perToken = foldl composeAnalyzers nullCheck $ mapMaybe include list
}
where
shell = shellType params
include (ForShell list a) = do
guard $ shell `elem` list
return a
checker params = getChecker params checks
checks = [
checkForDecimals
,checkBashisms
,checkEchoSed
,checkBraceExpansionVars
,checkMultiDimensionalArrays
,checkPS1Assignments
]
testChecker (ForShell _ t) =
Checker {
perScript = nullCheck,
perToken = t
}
verify c s = producesComments (testChecker c) s == Just True
verifyNot c s = producesComments (testChecker c) s == Just False
-- |
-- >>> prop $ verify checkForDecimals "((3.14*c))"
-- >>> prop $ verify checkForDecimals "foo[1.2]=bar"
-- >>> prop $ verifyNot checkForDecimals "declare -A foo; foo[1.2]=bar"
checkForDecimals = ForShell [Sh, Dash, Bash] f
where
f t@(TA_Expansion id _) = potentially $ do
str <- getLiteralString t
first <- str !!! 0
guard $ isDigit first && '.' `elem` str
return $ err id 2079 "(( )) doesn't support decimals. Use bc or awk."
f _ = return ()
-- |
-- >>> prop $ verify checkBashisms "while read a; do :; done < <(a)"
-- >>> prop $ verify checkBashisms "[ foo -nt bar ]"
-- >>> prop $ verify checkBashisms "echo $((i++))"
-- >>> prop $ verify checkBashisms "rm !(*.hs)"
-- >>> prop $ verify checkBashisms "source file"
-- >>> prop $ verify checkBashisms "[ \"$a\" == 42 ]"
-- >>> prop $ verify checkBashisms "echo ${var[1]}"
-- >>> prop $ verify checkBashisms "echo ${!var[@]}"
-- >>> prop $ verify checkBashisms "echo ${!var*}"
-- >>> prop $ verify checkBashisms "echo ${var:4:12}"
-- >>> prop $ verifyNot checkBashisms "echo ${var:-4}"
-- >>> prop $ verify checkBashisms "echo ${var//foo/bar}"
-- >>> prop $ verify checkBashisms "exec -c env"
-- >>> prop $ verify checkBashisms "echo -n \"Foo: \""
-- >>> prop $ verify checkBashisms "let n++"
-- >>> prop $ verify checkBashisms "echo $RANDOM"
-- >>> prop $ verify checkBashisms "echo $((RANDOM%6+1))"
-- >>> prop $ verify checkBashisms "foo &> /dev/null"
-- >>> prop $ verify checkBashisms "foo > file*.txt"
-- >>> prop $ verify checkBashisms "read -ra foo"
-- >>> prop $ verify checkBashisms "[ -a foo ]"
-- >>> prop $ verifyNot checkBashisms "[ foo -a bar ]"
-- >>> prop $ verify checkBashisms "trap mything ERR INT"
-- >>> prop $ verifyNot checkBashisms "trap mything INT TERM"
-- >>> prop $ verify checkBashisms "cat < /dev/tcp/host/123"
-- >>> prop $ verify checkBashisms "trap mything ERR SIGTERM"
-- >>> prop $ verify checkBashisms "echo *[^0-9]*"
-- >>> prop $ verify checkBashisms "exec {n}>&2"
-- >>> prop $ verify checkBashisms "echo ${!var}"
-- >>> prop $ verify checkBashisms "printf -v '%s' \"$1\""
-- >>> prop $ verify checkBashisms "printf '%q' \"$1\""
-- >>> prop $ verifyNot checkBashisms "#!/bin/dash\n[ foo -nt bar ]"
-- >>> prop $ verify checkBashisms "#!/bin/sh\necho -n foo"
-- >>> prop $ verifyNot checkBashisms "#!/bin/dash\necho -n foo"
-- >>> prop $ verifyNot checkBashisms "#!/bin/dash\nlocal foo"
-- >>> prop $ verifyNot checkBashisms "#!/bin/dash\nread -p foo -r bar"
-- >>> prop $ verifyNot checkBashisms "HOSTNAME=foo; echo $HOSTNAME"
-- >>> prop $ verify checkBashisms "RANDOM=9; echo $RANDOM"
-- >>> prop $ verify checkBashisms "foo-bar() { true; }"
-- >>> prop $ verify checkBashisms "echo $(<file)"
-- >>> prop $ verify checkBashisms "echo `<file`"
-- >>> prop $ verify checkBashisms "trap foo int"
-- >>> prop $ verify checkBashisms "trap foo sigint"
-- >>> prop $ verifyNot checkBashisms "#!/bin/dash\ntrap foo int"
-- >>> prop $ verifyNot checkBashisms "#!/bin/dash\ntrap foo INT"
-- >>> prop $ verify checkBashisms "#!/bin/dash\ntrap foo SIGINT"
-- >>> prop $ verify checkBashisms "#!/bin/dash\necho foo 42>/dev/null"
-- >>> prop $ verifyNot checkBashisms "#!/bin/sh\necho $LINENO"
-- >>> prop $ verify checkBashisms "#!/bin/dash\necho $MACHTYPE"
-- >>> prop $ verify checkBashisms "#!/bin/sh\ncmd >& file"
-- >>> prop $ verifyNot checkBashisms "#!/bin/sh\ncmd 2>&1"
-- >>> prop $ verifyNot checkBashisms "#!/bin/sh\ncmd >&2"
-- >>> prop $ verifyNot checkBashisms "#!/bin/sh\nprintf -- -f\n"
-- >>> prop $ verify checkBashisms "#!/bin/sh\nfoo+=bar"
-- >>> prop $ verify checkBashisms "#!/bin/sh\necho ${@%foo}"
-- >>> prop $ verifyNot checkBashisms "#!/bin/sh\necho ${##}"
checkBashisms = ForShell [Sh, Dash] $ \t -> do
params <- ask
kludge params t
where
-- This code was copy-pasted from Analytics where params was a variable
kludge params = bashism
where
isDash = shellType params == Dash
warnMsg id s =
if isDash
then warn id 2169 $ "In dash, " ++ s ++ " not supported."
else warn id 2039 $ "In POSIX sh, " ++ s ++ " undefined."
bashism (T_ProcSub id _ _) = warnMsg id "process substitution is"
bashism (T_Extglob id _ _) = warnMsg id "extglob is"
bashism (T_DollarSingleQuoted id _) = warnMsg id "$'..' is"
bashism (T_DollarDoubleQuoted id _) = warnMsg id "$\"..\" is"
bashism (T_ForArithmetic id _ _ _ _) = warnMsg id "arithmetic for loops are"
bashism (T_Arithmetic id _) = warnMsg id "standalone ((..)) is"
bashism (T_DollarBracket id _) = warnMsg id "$[..] in place of $((..)) is"
bashism (T_SelectIn id _ _ _) = warnMsg id "select loops are"
bashism (T_BraceExpansion id _) = warnMsg id "brace expansion is"
bashism (T_Condition id DoubleBracket _) = warnMsg id "[[ ]] is"
bashism (T_HereString id _) = warnMsg id "here-strings are"
bashism (TC_Binary id SingleBracket op _ _)
| op `elem` [ "<", ">", "\\<", "\\>", "<=", ">=", "\\<=", "\\>="] =
unless isDash $ warnMsg id $ "lexicographical " ++ op ++ " is"
bashism (TC_Binary id SingleBracket op _ _)
| op `elem` [ "-nt", "-ef" ] =
unless isDash $ warnMsg id $ op ++ " is"
bashism (TC_Binary id SingleBracket "==" _ _) =
warnMsg id "== in place of = is"
bashism (TC_Binary id SingleBracket "=~" _ _) =
warnMsg id "=~ regex matching is"
bashism (TC_Unary id _ "-a" _) =
warnMsg id "unary -a in place of -e is"
bashism (TA_Unary id op _)
| op `elem` [ "|++", "|--", "++|", "--|"] =
warnMsg id $ filter (/= '|') op ++ " is"
bashism (TA_Binary id "**" _ _) = warnMsg id "exponentials are"
bashism (T_FdRedirect id "&" (T_IoFile _ (T_Greater _) _)) = warnMsg id "&> is"
bashism (T_FdRedirect id "" (T_IoFile _ (T_GREATAND _) _)) = warnMsg id ">& is"
bashism (T_FdRedirect id ('{':_) _) = warnMsg id "named file descriptors are"
bashism (T_FdRedirect id num _)
| all isDigit num && length num > 1 = warnMsg id "FDs outside 0-9 are"
bashism (T_Assignment id Append _ _ _) =
warnMsg id "+= is"
bashism (T_IoFile id _ word) | isNetworked =
warnMsg id "/dev/{tcp,udp} is"
where
file = onlyLiteralString word
isNetworked = any (`isPrefixOf` file) ["/dev/tcp", "/dev/udp"]
bashism (T_Glob id str) | "[^" `isInfixOf` str =
warnMsg id "^ in place of ! in glob bracket expressions is"
bashism t@(TA_Variable id str _) | isBashVariable str =
warnMsg id $ str ++ " is"
bashism t@(T_DollarBraced id token) = do
mapM_ check expansion
when (isBashVariable var) $
warnMsg id $ var ++ " is"
where
str = bracedString t
var = getBracedReference str
check (regex, feature) =
when (isJust $ matchRegex regex str) $ warnMsg id feature
bashism t@(T_Pipe id "|&") =
warnMsg id "|& in place of 2>&1 | is"
bashism (T_Array id _) =
warnMsg id "arrays are"
bashism (T_IoFile id _ t) | isGlob t =
warnMsg id "redirecting to/from globs is"
bashism (T_CoProc id _ _) =
warnMsg id "coproc is"
bashism (T_Function id _ _ str _) | not (isVariableName str) =
warnMsg id "naming functions outside [a-zA-Z_][a-zA-Z0-9_]* is"
bashism (T_DollarExpansion id [x]) | isOnlyRedirection x =
warnMsg id "$(<file) to read files is"
bashism (T_Backticked id [x]) | isOnlyRedirection x =
warnMsg id "`<file` to read files is"
bashism t@(T_SimpleCommand _ _ (cmd:arg:_))
| t `isCommand` "echo" && "-" `isPrefixOf` argString =
unless ("--" `isPrefixOf` argString) $ -- echo "-----"
if isDash
then
when (argString /= "-n") $
warnMsg (getId arg) "echo flags besides -n"
else
warnMsg (getId arg) "echo flags are"
where argString = concat $ oversimplify arg
bashism t@(T_SimpleCommand _ _ (cmd:arg:_))
| t `isCommand` "exec" && "-" `isPrefixOf` concat (oversimplify arg) =
warnMsg (getId arg) "exec flags are"
bashism t@(T_SimpleCommand id _ _)
| t `isCommand` "let" = warnMsg id "'let' is"
bashism t@(T_SimpleCommand id _ (cmd:rest)) =
let name = fromMaybe "" $ getCommandName t
flags = getLeadingFlags t
in do
when (name `elem` unsupportedCommands) $
warnMsg id $ "'" ++ name ++ "' is"
potentially $ do
allowed <- Map.lookup name allowedFlags
(word, flag) <- listToMaybe $
filter (\x -> (not . null . snd $ x) && snd x `notElem` allowed) flags
return . warnMsg (getId word) $ name ++ " -" ++ flag ++ " is"
when (name == "source") $ warnMsg id "'source' in place of '.' is"
when (name == "trap") $
let
check token = potentially $ do
str <- getLiteralString token
let upper = map toUpper str
return $ do
when (upper `elem` ["ERR", "DEBUG", "RETURN"]) $
warnMsg (getId token) $ "trapping " ++ str ++ " is"
when ("SIG" `isPrefixOf` upper) $
warnMsg (getId token)
"prefixing signal names with 'SIG' is"
when (not isDash && upper /= str) $
warnMsg (getId token)
"using lower/mixed case for signal names is"
in
mapM_ check (drop 1 rest)
when (name == "printf") $ potentially $ do
format <- rest !!! 0 -- flags are covered by allowedFlags
let literal = onlyLiteralString format
guard $ "%q" `isInfixOf` literal
return $ warnMsg (getId format) "printf %q is"
where
unsupportedCommands = [
"let", "caller", "builtin", "complete", "compgen", "declare", "dirs", "disown",
"enable", "mapfile", "readarray", "pushd", "popd", "shopt", "suspend",
"typeset"
] ++ if not isDash then ["local"] else []
allowedFlags = Map.fromList [
("exec", []),
("export", ["-p"]),
("printf", []),
("read", if isDash then ["r", "p"] else ["r"]),
("ulimit", ["f"])
]
bashism t@(T_SourceCommand id src _) =
let name = fromMaybe "" $ getCommandName src
in do
when (name == "source") $ warnMsg id "'source' in place of '.' is"
bashism _ = return ()
varChars="_0-9a-zA-Z"
expansion = let re = mkRegex in [
(re $ "^![" ++ varChars ++ "]", "indirect expansion is"),
(re $ "^[" ++ varChars ++ "]+\\[.*\\]$", "array references are"),
(re $ "^![" ++ varChars ++ "]+\\[[*@]]$", "array key expansion is"),
(re $ "^![" ++ varChars ++ "]+[*@]$", "name matching prefixes are"),
(re $ "^[" ++ varChars ++ "*@]+:[^-=?+]", "string indexing is"),
(re $ "^([*@][%#]|#[@*])", "string operations on $@/$* are"),
(re $ "^[" ++ varChars ++ "*@]+(\\[.*\\])?/", "string replacement is")
]
bashVars = [
"OSTYPE", "MACHTYPE", "HOSTTYPE", "HOSTNAME",
"DIRSTACK", "EUID", "UID", "SHLVL", "PIPESTATUS", "SHELLOPTS"
]
bashDynamicVars = [ "RANDOM", "SECONDS" ]
dashVars = [ ]
isBashVariable var =
(var `elem` bashDynamicVars
|| var `elem` bashVars && not (isAssigned var))
&& not (isDash && var `elem` dashVars)
isAssigned var = any f (variableFlow params)
where
f x = case x of
Assignment (_, _, name, _) -> name == var
_ -> False
-- |
-- >>> prop $ verify checkEchoSed "FOO=$(echo \"$cow\" | sed 's/foo/bar/g')"
-- >>> prop $ verify checkEchoSed "rm $(echo $cow | sed -e 's,foo,bar,')"
checkEchoSed = ForShell [Bash, Ksh] f
where
f (T_Pipeline id _ [a, b]) =
when (acmd == ["echo", "${VAR}"]) $
case bcmd of
["sed", v] -> checkIn v
["sed", "-e", v] -> checkIn v
_ -> return ()
where
-- This should have used backreferences, but TDFA doesn't support them
sedRe = mkRegex "^s(.)([^\n]*)g?$"
isSimpleSed s = fromMaybe False $ do
[first,rest] <- matchRegex sedRe s
let delimiters = filter (== head first) rest
guard $ length delimiters == 2
return True
acmd = oversimplify a
bcmd = oversimplify b
checkIn s =
when (isSimpleSed s) $
style id 2001 "See if you can use ${variable//search/replace} instead."
f _ = return ()
-- |
-- >>> prop $ verify checkBraceExpansionVars "echo {1..$n}"
-- >>> prop $ verifyNot checkBraceExpansionVars "echo {1,3,$n}"
-- >>> prop $ verify checkBraceExpansionVars "eval echo DSC{0001..$n}.jpg"
-- >>> prop $ verify checkBraceExpansionVars "echo {$i..100}"
checkBraceExpansionVars = ForShell [Bash] f
where
f t@(T_BraceExpansion id list) = mapM_ check list
where
check element =
when (any (`isInfixOf` toString element) ["$..", "..$"]) $ do
c <- isEvaled element
if c
then style id 2175 "Quote this invalid brace expansion since it should be passed literally to eval."
else warn id 2051 "Bash doesn't support variables in brace range expansions."
f _ = return ()
literalExt t =
case t of
T_DollarBraced {} -> return "$"
T_DollarExpansion {} -> return "$"
T_DollarArithmetic {} -> return "$"
otherwise -> return "-"
toString t = fromJust $ getLiteralStringExt literalExt t
isEvaled t = do
cmd <- getClosestCommandM t
return $ isJust cmd && fromJust cmd `isUnqualifiedCommand` "eval"
-- |
-- >>> prop $ verify checkMultiDimensionalArrays "foo[a][b]=3"
-- >>> prop $ verifyNot checkMultiDimensionalArrays "foo[a]=3"
-- >>> prop $ verify checkMultiDimensionalArrays "foo=( [a][b]=c )"
-- >>> prop $ verifyNot checkMultiDimensionalArrays "foo=( [a]=c )"
-- >>> prop $ verify checkMultiDimensionalArrays "echo ${foo[bar][baz]}"
-- >>> prop $ verifyNot checkMultiDimensionalArrays "echo ${foo[bar]}"
checkMultiDimensionalArrays = ForShell [Bash] f
where
f token =
case token of
T_Assignment _ _ name (first:second:_) _ -> about second
T_IndexedElement _ (first:second:_) _ -> about second
T_DollarBraced {} ->
when (isMultiDim token) $ about token
_ -> return ()
about t = warn (getId t) 2180 "Bash does not support multidimensional arrays. Use 1D or associative arrays."
re = mkRegex "^\\[.*\\]\\[.*\\]" -- Fixme, this matches ${foo:- [][]} and such as well
isMultiDim t = getBracedModifier (bracedString t) `matches` re
-- |
-- >>> prop $ verify checkPS1Assignments "PS1='\\033[1;35m\\$ '"
-- >>> prop $ verify checkPS1Assignments "export PS1='\\033[1;35m\\$ '"
-- >>> prop $ verify checkPS1Assignments "PS1='\\h \\e[0m\\$ '"
-- >>> prop $ verify checkPS1Assignments "PS1=$'\\x1b[c '"
-- >>> prop $ verify checkPS1Assignments "PS1=$'\\e[3m; '"
-- >>> prop $ verify checkPS1Assignments "export PS1=$'\\e[3m; '"
-- >>> prop $ verifyNot checkPS1Assignments "PS1='\\[\\033[1;35m\\]\\$ '"
-- >>> prop $ verifyNot checkPS1Assignments "PS1='\\[\\e1m\\e[1m\\]\\$ '"
-- >>> prop $ verifyNot checkPS1Assignments "PS1='e033x1B'"
-- >>> prop $ verifyNot checkPS1Assignments "PS1='\\[\\e\\]'"
checkPS1Assignments = ForShell [Bash] f
where
f token = case token of
(T_Assignment _ _ "PS1" _ word) -> warnFor word
_ -> return ()
warnFor word =
let contents = concat $ oversimplify word in
when (containsUnescaped contents) $
info (getId word) 2025 "Make sure all escape sequences are enclosed in \\[..\\] to prevent line wrapping issues"
containsUnescaped s =
let unenclosed = subRegex enclosedRegex s "" in
isJust $ matchRegex escapeRegex unenclosed
enclosedRegex = mkRegex "\\\\\\[.*\\\\\\]" -- FIXME: shouldn't be eager
escapeRegex = mkRegex "\\\\x1[Bb]|\\\\e|\x1B|\\\\033"

117
src/ShellCheck/Data.hs Normal file
View File

@@ -0,0 +1,117 @@
module ShellCheck.Data where
import ShellCheck.Interface
import Data.Version (showVersion)
import Paths_ShellCheck (version)
shellcheckVersion = showVersion version
internalVariables = [
-- Generic
"", "_", "rest", "REST",
-- Bash
"BASH", "BASHOPTS", "BASHPID", "BASH_ALIASES", "BASH_ARGC",
"BASH_ARGV", "BASH_CMDS", "BASH_COMMAND", "BASH_EXECUTION_STRING",
"BASH_LINENO", "BASH_REMATCH", "BASH_SOURCE", "BASH_SUBSHELL",
"BASH_VERSINFO", "BASH_VERSION", "COMP_CWORD", "COMP_KEY",
"COMP_LINE", "COMP_POINT", "COMP_TYPE", "COMP_WORDBREAKS",
"COMP_WORDS", "COPROC", "DIRSTACK", "EUID", "FUNCNAME", "GROUPS",
"HISTCMD", "HOSTNAME", "HOSTTYPE", "LINENO", "MACHTYPE", "MAPFILE",
"OLDPWD", "OPTARG", "OPTIND", "OSTYPE", "PIPESTATUS", "PPID", "PWD",
"RANDOM", "READLINE_LINE", "READLINE_POINT", "REPLY", "SECONDS",
"SHELLOPTS", "SHLVL", "UID", "BASH_ENV", "BASH_XTRACEFD", "CDPATH",
"COLUMNS", "COMPREPLY", "EMACS", "ENV", "FCEDIT", "FIGNORE",
"FUNCNEST", "GLOBIGNORE", "HISTCONTROL", "HISTFILE", "HISTFILESIZE",
"HISTIGNORE", "HISTSIZE", "HISTTIMEFORMAT", "HOME", "HOSTFILE", "IFS",
"IGNOREEOF", "INPUTRC", "LANG", "LC_ALL", "LC_COLLATE", "LC_CTYPE",
"LC_MESSAGES", "LC_MONETARY", "LC_NUMERIC", "LC_TIME", "LINES", "MAIL",
"MAILCHECK", "MAILPATH", "OPTERR", "PATH", "POSIXLY_CORRECT",
"PROMPT_COMMAND", "PROMPT_DIRTRIM", "PS1", "PS2", "PS3", "PS4", "SHELL",
"TIMEFORMAT", "TMOUT", "TMPDIR", "auto_resume", "histchars", "COPROC",
-- Other
"USER", "TZ", "TERM", "LOGNAME", "LD_LIBRARY_PATH", "LANGUAGE", "DISPLAY",
"HOSTNAME", "KRB5CCNAME", "XAUTHORITY"
-- Ksh
, ".sh.version"
]
variablesWithoutSpaces = [
"$", "-", "?", "!", "#",
"BASHPID", "BASH_ARGC", "BASH_LINENO", "BASH_SUBSHELL", "EUID", "LINENO",
"OPTIND", "PPID", "RANDOM", "SECONDS", "SHELLOPTS", "SHLVL", "UID",
"COLUMNS", "HISTFILESIZE", "HISTSIZE", "LINES"
]
arrayVariables = [
"BASH_ALIASES", "BASH_ARGC", "BASH_ARGV", "BASH_CMDS", "BASH_LINENO",
"BASH_REMATCH", "BASH_SOURCE", "BASH_VERSINFO", "COMP_WORDS", "COPROC",
"DIRSTACK", "FUNCNAME", "GROUPS", "MAPFILE", "PIPESTATUS", "COMPREPLY"
]
commonCommands = [
"admin", "alias", "ar", "asa", "at", "awk", "basename", "batch",
"bc", "bg", "break", "c99", "cal", "cat", "cd", "cflow", "chgrp",
"chmod", "chown", "cksum", "cmp", "colon", "comm", "command",
"compress", "continue", "cp", "crontab", "csplit", "ctags", "cut",
"cxref", "date", "dd", "delta", "df", "diff", "dirname", "dot",
"du", "echo", "ed", "env", "eval", "ex", "exec", "exit", "expand",
"export", "expr", "fc", "fg", "file", "find", "fold", "fort77",
"fuser", "gencat", "get", "getconf", "getopts", "grep", "hash",
"head", "iconv", "ipcrm", "ipcs", "jobs", "join", "kill", "lex",
"link", "ln", "locale", "localedef", "logger", "logname", "lp",
"ls", "m4", "mailx", "make", "man", "mesg", "mkdir", "mkfifo",
"more", "mv", "newgrp", "nice", "nl", "nm", "nohup", "od", "paste",
"patch", "pathchk", "pax", "pr", "printf", "prs", "ps", "pwd",
"qalter", "qdel", "qhold", "qmove", "qmsg", "qrerun", "qrls",
"qselect", "qsig", "qstat", "qsub", "read", "readonly", "renice",
"return", "rm", "rmdel", "rmdir", "sact", "sccs", "sed", "set",
"sh", "shift", "sleep", "sort", "split", "strings", "strip", "stty",
"tabs", "tail", "talk", "tee", "test", "time", "times", "touch",
"tput", "tr", "trap", "tsort", "tty", "type", "ulimit", "umask",
"unalias", "uname", "uncompress", "unexpand", "unget", "uniq",
"unlink", "unset", "uucp", "uudecode", "uuencode", "uustat", "uux",
"val", "vi", "wait", "wc", "what", "who", "write", "xargs", "yacc",
"zcat"
]
nonReadingCommands = [
"alias", "basename", "bg", "cal", "cd", "chgrp", "chmod", "chown",
"cp", "du", "echo", "export", "false", "fg", "fuser", "getconf",
"getopt", "getopts", "ipcrm", "ipcs", "jobs", "kill", "ln", "ls",
"locale", "mv", "printf", "ps", "pwd", "renice", "rm", "rmdir",
"set", "sleep", "touch", "trap", "true", "ulimit", "unalias", "uname"
]
sampleWords = [
"alpha", "bravo", "charlie", "delta", "echo", "foxtrot",
"golf", "hotel", "india", "juliett", "kilo", "lima", "mike",
"november", "oscar", "papa", "quebec", "romeo", "sierra",
"tango", "uniform", "victor", "whiskey", "xray", "yankee",
"zulu"
]
binaryTestOps = [
"-nt", "-ot", "-ef", "==", "!=", "<=", ">=", "-eq", "-ne", "-lt", "-le",
"-gt", "-ge", "=~", ">", "<", "=", "\\<", "\\>", "\\<=", "\\>="
]
unaryTestOps = [
"!", "-a", "-b", "-c", "-d", "-e", "-f", "-g", "-h", "-L", "-k", "-p",
"-r", "-s", "-S", "-t", "-u", "-w", "-x", "-O", "-G", "-N", "-z", "-n",
"-o", "-v", "-R"
]
shellForExecutable :: String -> Maybe Shell
shellForExecutable name =
case name of
"sh" -> return Sh
"bash" -> return Bash
"dash" -> return Dash
"ash" -> return Dash -- There's also a warning for this.
"ksh" -> return Ksh
"ksh88" -> return Ksh
"ksh93" -> return Ksh
otherwise -> Nothing

View File

@@ -0,0 +1,95 @@
{-
Copyright 2012-2015 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/>.
-}
module ShellCheck.Formatter.CheckStyle (format) where
import ShellCheck.Interface
import ShellCheck.Formatter.Format
import Data.Char
import Data.List
import GHC.Exts
import System.IO
format :: IO Formatter
format = return Formatter {
header = do
putStrLn "<?xml version='1.0' encoding='UTF-8'?>"
putStrLn "<checkstyle version='4.3'>",
onFailure = outputError,
onResult = outputResults,
footer = putStrLn "</checkstyle>"
}
outputResults cr sys =
if null comments
then outputFile (crFilename cr) "" []
else mapM_ outputGroup fileGroups
where
comments = crComments cr
fileGroups = groupWith sourceFile comments
outputGroup group = do
let filename = sourceFile (head group)
result <- (siReadFile sys) filename
let contents = either (const "") id result
outputFile filename contents group
outputFile filename contents warnings = do
let comments = makeNonVirtual warnings contents
putStrLn . formatFile filename $ comments
formatFile name comments = concat [
"<file ", attr "name" name, ">\n",
concatMap formatComment comments,
"</file>"
]
formatComment c = concat [
"<error ",
attr "line" $ show . lineNo $ c,
attr "column" $ show . colNo $ c,
attr "severity" . severity $ severityText c,
attr "message" $ messageText c,
attr "source" $ "ShellCheck.SC" ++ show (codeNo c),
"/>\n"
]
outputError file error = putStrLn $ concat [
"<file ", attr "name" file, ">\n",
"<error ",
attr "line" "1",
attr "column" "1",
attr "severity" "error",
attr "message" error,
attr "source" "ShellCheck",
"/>\n",
"</file>"
]
attr s v = concat [ s, "='", escape v, "' " ]
escape = concatMap escape'
escape' c = if isOk c then [c] else "&#" ++ show (ord c) ++ ";"
isOk x = any ($x) [isAsciiUpper, isAsciiLower, isDigit, (`elem` " ./")]
severity "error" = "error"
severity "warning" = "warning"
severity _ = "info"

View File

@@ -0,0 +1,70 @@
{-
Copyright 2012-2015 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/>.
-}
module ShellCheck.Formatter.Format where
import ShellCheck.Data
import ShellCheck.Interface
-- A formatter that carries along an arbitrary piece of data
data Formatter = Formatter {
header :: IO (),
onResult :: CheckResult -> SystemInterface IO -> IO (),
onFailure :: FilePath -> ErrorMessage -> IO (),
footer :: IO ()
}
sourceFile = posFile . pcStartPos
lineNo = posLine . pcStartPos
endLineNo = posLine . pcEndPos
colNo = posColumn . pcStartPos
endColNo = posColumn . pcEndPos
codeNo = cCode . pcComment
messageText = cMessage . pcComment
severityText :: PositionedComment -> String
severityText pc =
case cSeverity (pcComment pc) of
ErrorC -> "error"
WarningC -> "warning"
InfoC -> "info"
StyleC -> "style"
-- Realign comments from a tabstop of 8 to 1
makeNonVirtual comments contents =
map fix comments
where
ls = lines contents
fix c = c {
pcStartPos = (pcStartPos c) {
posColumn = realignColumn lineNo colNo c
}
, pcEndPos = (pcEndPos c) {
posColumn = realignColumn endLineNo endColNo c
}
}
realignColumn lineNo colNo c =
if lineNo c > 0 && lineNo c <= fromIntegral (length ls)
then real (ls !! fromIntegral (lineNo c - 1)) 0 0 (colNo c)
else colNo c
real _ r v target | target <= v = r
real [] r v _ = r -- should never happen
real ('\t':rest) r v target =
real rest (r+1) (v + 8 - (v `mod` 8)) target
real (_:rest) r v target = real rest (r+1) (v+1) target

View File

@@ -0,0 +1,65 @@
{-
Copyright 2012-2015 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/>.
-}
module ShellCheck.Formatter.GCC (format) where
import ShellCheck.Interface
import ShellCheck.Formatter.Format
import Data.List
import GHC.Exts
import System.IO
format :: IO Formatter
format = return Formatter {
header = return (),
footer = return (),
onFailure = outputError,
onResult = outputAll
}
outputError file error = hPutStrLn stderr $ file ++ ": " ++ error
outputAll cr sys = mapM_ f groups
where
comments = crComments cr
groups = groupWith sourceFile comments
f :: [PositionedComment] -> IO ()
f group = do
let filename = sourceFile (head group)
result <- (siReadFile sys) filename
let contents = either (const "") id result
outputResult filename contents group
outputResult filename contents warnings = do
let comments = makeNonVirtual warnings contents
mapM_ (putStrLn . formatComment filename) comments
formatComment filename c = concat [
filename, ":",
show $ lineNo c, ":",
show $ colNo c, ": ",
case severityText c of
"error" -> "error"
"warning" -> "warning"
_ -> "note",
": ",
concat . lines $ messageText c,
" [SC", show $ codeNo c, "]"
]

View File

@@ -0,0 +1,99 @@
{-# LANGUAGE OverloadedStrings #-}
{-
Copyright 2012-2015 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/>.
-}
module ShellCheck.Formatter.JSON (format) where
import ShellCheck.Interface
import ShellCheck.Formatter.Format
import Data.Aeson
import Data.IORef
import Data.Monoid
import GHC.Exts
import System.IO
import qualified Data.ByteString.Lazy.Char8 as BL
format = do
ref <- newIORef []
return Formatter {
header = return (),
onResult = collectResult ref,
onFailure = outputError,
footer = finish ref
}
instance ToJSON Replacement where
toJSON replacement =
let start = repStartPos replacement
end = repEndPos replacement
str = repString replacement in
object [
"line" .= posLine start,
"endLine" .= posLine end,
"column" .= posColumn start,
"endColumn" .= posColumn end,
"replaceWith" .= str
]
instance ToJSON PositionedComment where
toJSON comment =
let start = pcStartPos comment
end = pcEndPos comment
c = pcComment comment in
object [
"file" .= posFile start,
"line" .= posLine start,
"endLine" .= posLine end,
"column" .= posColumn start,
"endColumn" .= posColumn end,
"level" .= severityText comment,
"code" .= cCode c,
"message" .= cMessage c,
"fix" .= pcFix comment
]
toEncoding comment =
let start = pcStartPos comment
end = pcEndPos comment
c = pcComment comment in
pairs (
"file" .= posFile start
<> "line" .= posLine start
<> "endLine" .= posLine end
<> "column" .= posColumn start
<> "endColumn" .= posColumn end
<> "level" .= severityText comment
<> "code" .= cCode c
<> "message" .= cMessage c
<> "fix" .= pcFix comment
)
instance ToJSON Fix where
toJSON fix = object [
"replacements" .= fixReplacements fix
]
outputError file msg = hPutStrLn stderr $ file ++ ": " ++ msg
collectResult ref result _ =
modifyIORef ref (\x -> crComments result ++ x)
finish ref = do
list <- readIORef ref
BL.putStrLn $ encode list

View File

@@ -0,0 +1,213 @@
{-
Copyright 2012-2015 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/>.
-}
module ShellCheck.Formatter.TTY (format) where
import ShellCheck.Interface
import ShellCheck.Formatter.Format
import Control.Monad
import Data.IORef
import Data.List
import Data.Maybe
import GHC.Exts
import System.IO
import System.Info
wikiLink = "https://www.shellcheck.net/wiki/"
-- An arbitrary Ord thing to order warnings
type Ranking = (Char, Severity, Integer)
format :: FormatterOptions -> IO Formatter
format options = do
topErrorRef <- newIORef []
return Formatter {
header = return (),
footer = outputWiki topErrorRef,
onFailure = outputError options,
onResult = outputResult options topErrorRef
}
colorForLevel level =
case level of
"error" -> 31 -- red
"warning" -> 33 -- yellow
"info" -> 32 -- green
"style" -> 32 -- green
"message" -> 1 -- bold
"source" -> 0 -- none
_ -> 0 -- none
rankError :: PositionedComment -> Ranking
rankError err = (ranking, cSeverity $ pcComment err, cCode $ pcComment err)
where
ranking =
if cCode (pcComment err) `elem` uninteresting
then 'Z'
else 'A'
-- A list of the most generic, least directly helpful
-- error codes to downrank.
uninteresting = [
1009, -- Mentioned parser error was..
1019, -- Expected this to be an argument
1036, -- ( is invalid here
1047, -- Expected 'fi'
1062, -- Expected 'done'
1070, -- Parsing stopped here (generic)
1072, -- Missing/unexpected ..
1073, -- Couldn't parse this ..
1088, -- Parsing stopped here (paren)
1089 -- Parsing stopped here (keyword)
]
appendComments errRef comments max = do
previous <- readIORef errRef
let current = map (\x -> (rankError x, cCode $ pcComment x, cMessage $ pcComment x)) comments
writeIORef errRef . take max . nubBy equal . sort $ previous ++ current
where
fst3 (x,_,_) = x
equal x y = fst3 x == fst3 y
outputWiki :: IORef [(Ranking, Integer, String)] -> IO ()
outputWiki errRef = do
issues <- readIORef errRef
unless (null issues) $ do
putStrLn "For more information:"
mapM_ showErr issues
where
showErr (_, code, msg) =
putStrLn $ " " ++ wikiLink ++ "SC" ++ show code ++ " -- " ++ shorten msg
limit = 36
shorten msg =
if length msg < limit
then msg
else (take (limit-3) msg) ++ "..."
outputError options file error = do
color <- getColorFunc $ foColorOption options
hPutStrLn stderr $ color "error" $ file ++ ": " ++ error
outputResult options ref result sys = do
color <- getColorFunc $ foColorOption options
let comments = crComments result
appendComments ref comments (fromIntegral $ foWikiLinkCount options)
let fileGroups = groupWith sourceFile comments
mapM_ (outputForFile color sys) fileGroups
outputForFile color sys comments = do
let fileName = sourceFile (head comments)
result <- (siReadFile sys) fileName
let contents = either (const "") id result
let fileLines = lines contents
let lineCount = fromIntegral $ length fileLines
let groups = groupWith lineNo comments
mapM_ (\commentsForLine -> do
let lineNum = lineNo (head commentsForLine)
let line = if lineNum < 1 || lineNum > lineCount
then ""
else fileLines !! fromIntegral (lineNum - 1)
putStrLn ""
putStrLn $ color "message" $
"In " ++ fileName ++" line " ++ show lineNum ++ ":"
putStrLn (color "source" line)
mapM_ (\c -> putStrLn (color (severityText c) $ cuteIndent c)) commentsForLine
putStrLn ""
showFixedString color comments lineNum line
) groups
hasApplicableFix lineNum comment = fromMaybe False $ do
replacements <- fixReplacements <$> pcFix comment
guard $ all (\c -> onSameLine (repStartPos c) && onSameLine (repEndPos c)) replacements
return True
where
onSameLine pos = posLine pos == lineNum
-- FIXME: Work correctly with multiple replacements
showFixedString color comments lineNum line =
case filter (hasApplicableFix lineNum) comments of
(first:_) -> do
-- in the spirit of error prone
putStrLn $ color "message" "Did you mean: "
putStrLn $ fixedString first line
putStrLn ""
_ -> return ()
-- need to do something smart about sorting by end index
fixedString :: PositionedComment -> String -> String
fixedString comment line =
case (pcFix comment) of
Nothing -> ""
Just rs ->
applyReplacement (fixReplacements rs) line 0
where
applyReplacement [] s _ = s
applyReplacement (rep:xs) s offset =
let replacementString = repString rep
start = (posColumn . repStartPos) rep
end = (posColumn . repEndPos) rep
z = doReplace start end s replacementString
len_r = (fromIntegral . length) replacementString in
applyReplacement xs z (offset + (end - start) + len_r)
-- FIXME: Work correctly with tabs
-- start and end comes from pos, which is 1 based
-- doReplace 0 0 "1234" "A" -> "A1234" -- technically not valid
-- doReplace 1 1 "1234" "A" -> "A1234"
-- doReplace 1 2 "1234" "A" -> "A234"
-- doReplace 3 3 "1234" "A" -> "12A34"
-- doReplace 4 4 "1234" "A" -> "123A4"
-- doReplace 5 5 "1234" "A" -> "1234A"
doReplace start end o r =
let si = fromIntegral (start-1)
ei = fromIntegral (end-1)
(x, xs) = splitAt si o
(y, z) = splitAt (ei - si) xs
in
x ++ r ++ z
cuteIndent :: PositionedComment -> String
cuteIndent comment =
replicate (fromIntegral $ colNo comment - 1) ' ' ++
makeArrow ++ " " ++ code (codeNo comment) ++ ": " ++ messageText comment
where
arrow n = '^' : replicate (fromIntegral $ n-2) '-' ++ "^"
makeArrow =
let sameLine = lineNo comment == endLineNo comment
delta = endColNo comment - colNo comment
in
if sameLine && delta > 2 && delta < 32 then arrow delta else "^--"
code num = "SC" ++ show num
getColorFunc colorOption = do
term <- hIsTerminalDevice stdout
let windows = "mingw" `isPrefixOf` os
let isUsableTty = term && not windows
let useColor = case colorOption of
ColorAlways -> True
ColorNever -> False
ColorAuto -> isUsableTty
return $ if useColor then colorComment else const id
where
colorComment level comment =
ansi (colorForLevel level) ++ comment ++ clear
clear = ansi 0
ansi n = "\x1B[" ++ show n ++ "m"

269
src/ShellCheck/Interface.hs Normal file
View File

@@ -0,0 +1,269 @@
{-
Copyright 2012-2015 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 #-}
module ShellCheck.Interface
(
SystemInterface(..)
, CheckSpec(csFilename, csScript, csCheckSourced, csExcludedWarnings, csShellTypeOverride, csMinSeverity)
, CheckResult(crFilename, crComments)
, ParseSpec(psFilename, psScript, psCheckSourced, psShellTypeOverride)
, ParseResult(prComments, prTokenPositions, prRoot)
, AnalysisSpec(asScript, asShellType, asExecutionMode, asCheckSourced, asTokenPositions)
, AnalysisResult(arComments)
, FormatterOptions(foColorOption, foWikiLinkCount)
, Shell(Ksh, Sh, Bash, Dash)
, ExecutionMode(Executed, Sourced)
, ErrorMessage
, Code
, Severity(ErrorC, WarningC, InfoC, StyleC)
, Position(posFile, posLine, posColumn)
, Comment(cSeverity, cCode, cMessage)
, PositionedComment(pcStartPos , pcEndPos , pcComment, pcFix)
, ColorOption(ColorAuto, ColorAlways, ColorNever)
, TokenComment(tcId, tcComment, tcFix)
, emptyCheckResult
, newParseResult
, newAnalysisSpec
, newAnalysisResult
, newFormatterOptions
, newPosition
, newTokenComment
, mockedSystemInterface
, newParseSpec
, emptyCheckSpec
, newPositionedComment
, newComment
, Fix(fixReplacements)
, newFix
, Replacement(repStartPos, repEndPos, repString)
, newReplacement
) where
import ShellCheck.AST
import Control.DeepSeq
import Control.Monad.Identity
import Data.Monoid
import GHC.Generics (Generic)
import qualified Data.Map as Map
newtype SystemInterface m = SystemInterface {
-- Read a file by filename, or return an error
siReadFile :: String -> m (Either ErrorMessage String)
}
-- ShellCheck input and output
data CheckSpec = CheckSpec {
csFilename :: String,
csScript :: String,
csCheckSourced :: Bool,
csExcludedWarnings :: [Integer],
csShellTypeOverride :: Maybe Shell,
csMinSeverity :: Severity
} deriving (Show, Eq)
data CheckResult = CheckResult {
crFilename :: String,
crComments :: [PositionedComment]
} deriving (Show, Eq)
emptyCheckResult :: CheckResult
emptyCheckResult = CheckResult {
crFilename = "",
crComments = []
}
emptyCheckSpec :: CheckSpec
emptyCheckSpec = CheckSpec {
csFilename = "",
csScript = "",
csCheckSourced = False,
csExcludedWarnings = [],
csShellTypeOverride = Nothing,
csMinSeverity = StyleC
}
newParseSpec :: ParseSpec
newParseSpec = ParseSpec {
psFilename = "",
psScript = "",
psCheckSourced = False,
psShellTypeOverride = Nothing
}
-- Parser input and output
data ParseSpec = ParseSpec {
psFilename :: String,
psScript :: String,
psCheckSourced :: Bool,
psShellTypeOverride :: Maybe Shell
} deriving (Show, Eq)
data ParseResult = ParseResult {
prComments :: [PositionedComment],
prTokenPositions :: Map.Map Id (Position, Position),
prRoot :: Maybe Token
} deriving (Show, Eq)
newParseResult :: ParseResult
newParseResult = ParseResult {
prComments = [],
prTokenPositions = Map.empty,
prRoot = Nothing
}
-- Analyzer input and output
data AnalysisSpec = AnalysisSpec {
asScript :: Token,
asShellType :: Maybe Shell,
asExecutionMode :: ExecutionMode,
asCheckSourced :: Bool,
asTokenPositions :: Map.Map Id (Position, Position)
}
newAnalysisSpec token = AnalysisSpec {
asScript = token,
asShellType = Nothing,
asExecutionMode = Executed,
asCheckSourced = False,
asTokenPositions = Map.empty
}
newtype AnalysisResult = AnalysisResult {
arComments :: [TokenComment]
}
newAnalysisResult = AnalysisResult {
arComments = []
}
-- Formatter options
data FormatterOptions = FormatterOptions {
foColorOption :: ColorOption,
foWikiLinkCount :: Integer
}
newFormatterOptions = FormatterOptions {
foColorOption = ColorAuto,
foWikiLinkCount = 3
}
-- Supporting data types
data Shell = Ksh | Sh | Bash | Dash deriving (Show, Eq)
data ExecutionMode = Executed | Sourced deriving (Show, Eq)
type ErrorMessage = String
type Code = Integer
data Severity = ErrorC | WarningC | InfoC | StyleC
deriving (Show, Eq, Ord, Generic, NFData)
data Position = Position {
posFile :: String, -- Filename
posLine :: Integer, -- 1 based source line
posColumn :: Integer -- 1 based source column, where tabs are 8
} deriving (Show, Eq, Generic, NFData)
newPosition :: Position
newPosition = Position {
posFile = "",
posLine = 1,
posColumn = 1
}
data Comment = Comment {
cSeverity :: Severity,
cCode :: Code,
cMessage :: String
} deriving (Show, Eq, Generic, NFData)
newComment :: Comment
newComment = Comment {
cSeverity = StyleC,
cCode = 0,
cMessage = ""
}
-- only support single line for now
data Replacement = Replacement {
repStartPos :: Position,
repEndPos :: Position,
repString :: String
} deriving (Show, Eq, Generic, NFData)
newReplacement = Replacement {
repStartPos = newPosition,
repEndPos = newPosition,
repString = ""
}
data Fix = Fix {
fixReplacements :: [Replacement]
} deriving (Show, Eq, Generic, NFData)
newFix = Fix {
fixReplacements = []
}
data PositionedComment = PositionedComment {
pcStartPos :: Position,
pcEndPos :: Position,
pcComment :: Comment,
pcFix :: Maybe Fix
} deriving (Show, Eq, Generic, NFData)
newPositionedComment :: PositionedComment
newPositionedComment = PositionedComment {
pcStartPos = newPosition,
pcEndPos = newPosition,
pcComment = newComment,
pcFix = Nothing
}
data TokenComment = TokenComment {
tcId :: Id,
tcComment :: Comment,
tcFix :: Maybe Fix
} deriving (Show, Eq, Generic, NFData)
newTokenComment = TokenComment {
tcId = Id 0,
tcComment = newComment,
tcFix = Nothing
}
data ColorOption =
ColorAuto
| ColorAlways
| ColorNever
deriving (Ord, Eq, Show)
-- For testing
mockedSystemInterface :: [(String, String)] -> SystemInterface Identity
mockedSystemInterface files = SystemInterface {
siReadFile = rf
}
where
rf file =
case filter ((== file) . fst) files of
[] -> return $ Left "File not included in mock."
[(_, contents)] -> return $ Right contents

3343
src/ShellCheck/Parser.hs Normal file

File diff suppressed because it is too large Load Diff

80
src/ShellCheck/Regex.hs Normal file
View File

@@ -0,0 +1,80 @@
{-
Copyright 2012-2015 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 FlexibleContexts #-}
-- Basically Text.Regex based on regex-tdfa instead of the buggy regex-posix.
module ShellCheck.Regex where
import Data.List
import Data.Maybe
import Control.Monad
import Text.Regex.TDFA
-- Precompile the regex
mkRegex :: String -> Regex
mkRegex str =
let make :: RegexMaker Regex CompOption ExecOption String => String -> Regex
make = makeRegex
in
make str
-- Does the regex match?
matches :: String -> Regex -> Bool
matches = flip match
-- Get all subgroups of the first match
matchRegex :: Regex -> String -> Maybe [String]
matchRegex re str = do
(_, _, _, groups) <- matchM re str :: Maybe (String,String,String,[String])
return groups
-- Get all full matches
matchAllStrings :: Regex -> String -> [String]
matchAllStrings re = unfoldr f
where
f :: String -> Maybe (String, String)
f str = do
(_, match, rest, _) <- matchM re str :: Maybe (String, String, String, [String])
return (match, rest)
-- Get all subgroups from all matches
matchAllSubgroups :: Regex -> String -> [[String]]
matchAllSubgroups re = unfoldr f
where
f :: String -> Maybe ([String], String)
f str = do
(_, _, rest, groups) <- matchM re str :: Maybe (String, String, String, [String])
return (groups, rest)
-- Replace regex in input with string
subRegex :: Regex -> String -> String -> String
subRegex re input replacement = f input
where
f str = fromMaybe str $ do
(before, match, after) <- matchM re str :: Maybe (String, String, String)
when (null match) $ error ("Internal error: substituted empty in " ++ str)
return $ before ++ replacement ++ f after
-- Split a string based on a regex.
splitOn :: String -> Regex -> [String]
splitOn input re =
case matchM re input :: Maybe (String, String, String) of
Just (before, match, after) -> before : after `splitOn` re
Nothing -> [input]

3
stack.yaml Normal file
View File

@@ -0,0 +1,3 @@
resolver: lts-12.9
packages:
- '.'

2
striptests Executable file
View File

@@ -0,0 +1,2 @@
#!/usr/bin/env bash
# This file was deprecated by the doctest build.

35
test/buildtest Executable file
View File

@@ -0,0 +1,35 @@
#!/bin/bash
# This script configures, builds and runs tests.
# It's meant for automatic cross-distro testing.
die() { echo "$*" >&2; exit 1; }
[ -e "ShellCheck.cabal" ] ||
die "ShellCheck.cabal not in current dir"
command -v cabal ||
die "cabal is missing"
cabal update ||
die "can't update"
cabal install --dependencies-only --enable-tests ||
die "can't install dependencies"
cabal configure --enable-tests ||
die "configure failed"
cabal build ||
die "build failed"
cabal test ||
die "test failed"
dist/build/shellcheck/shellcheck - << 'EOF' || die "execution failed"
#!/bin/sh
echo "Hello World"
EOF
dist/build/shellcheck/shellcheck - << 'EOF' && die "negative execution failed"
#!/bin/sh
echo $1
EOF
echo "Success"
exit 0

80
test/distrotest Executable file
View File

@@ -0,0 +1,80 @@
#!/bin/bash
# This script runs 'buildtest' on each of several distros
# via Docker.
set -o pipefail
exec 3>&1 4>&2
die() { echo "$*" >&4; exit 1; }
[ -e "ShellCheck.cabal" ] || die "ShellCheck.cabal not in this dir"
[ "$1" = "--run" ] || {
cat << EOF
This script pulls multiple distros via Docker and compiles
ShellCheck and dependencies for each one. It takes hours,
and is still highly experimental.
Make sure you're plugged in and have screen/tmux in place,
then re-run with $0 --run to continue.
Also note that 'dist' will be deleted.
EOF
exit 0
}
echo "Deleting 'dist'..."
rm -rf dist
log=$(mktemp) || die "Can't create temp file"
date >> "$log" || die "Can't write to log"
echo "Logging to $log" >&3
exec >> "$log" 2>&1
final=0
while read -r distro setup
do
[[ "$distro" = "#"* || -z "$distro" ]] && continue
printf '%s ' "$distro" >&3
docker pull "$distro" || die "Can't pull $distro"
printf 'pulled. ' >&3
tmp=$(mktemp -d) || die "Can't make temp dir"
cp -r . "$tmp/" || die "Can't populate test dir"
printf 'Result: ' >&3
< /dev/null docker run -v "$tmp:/mnt" "$distro" sh -c "
$setup
cd /mnt || exit 1
test/buildtest
"
ret=$?
if [ "$ret" = 0 ]
then
echo "OK" >&3
else
echo "FAIL with $ret. See $log" >&3
final=1
fi
rm -rf "$tmp"
done << EOF
# Docker tag Setup command
debian:stable apt-get update && apt-get install -y cabal-install
debian:testing apt-get update && apt-get install -y cabal-install
ubuntu:latest apt-get update && apt-get install -y cabal-install
opensuse:latest zypper install -y cabal-install ghc
# Older Ubuntu versions we want to support
ubuntu:18.04 apt-get update && apt-get install -y cabal-install
ubuntu:17.10 apt-get update && apt-get install -y cabal-install
# Misc Haskell including current and latest Stack build
ubuntu:18.10 set -e; apt-get update && apt-get install -y curl && curl -sSL https://get.haskellstack.org/ | sh -s - -f && cd /mnt && exec test/stacktest
haskell:latest true
# Known to currently fail
centos:latest yum install -y epel-release && yum install -y cabal-install
fedora:latest dnf install -y cabal-install
base/archlinux:latest pacman -S -y --noconfirm cabal-install ghc-static base-devel
EOF
exit "$final"

12
test/doctests.hs Normal file
View File

@@ -0,0 +1,12 @@
module Main where
import Build_doctests (flags, pkgs, module_sources)
import Data.Foldable (traverse_)
import Test.DocTest (doctest)
main :: IO ()
main = do
traverse_ putStrLn args
doctest args
where
args = flags ++ pkgs ++ module_sources

27
test/stacktest Executable file
View File

@@ -0,0 +1,27 @@
#!/bin/bash
# This script builds ShellCheck through `stack` using
# various resolvers. It's run via distrotest.
resolvers=(
nightly-"$(date -d "3 days ago" +"%Y-%m-%d")"
)
die() { echo "$*" >&2; exit 1; }
[ -e "ShellCheck.cabal" ] ||
die "ShellCheck.cabal not in current dir"
[ -e "stack.yaml" ] ||
die "stack.yaml not in current dir"
command -v stack ||
die "stack is missing"
stack setup || die "Failed to setup with default resolver"
stack build --test || die "Failed to build/test with default resolver"
for resolver in "${resolvers[@]}"
do
stack --resolver="$resolver" setup || die "Failed to setup $resolver"
stack --resolver="$resolver" build --test || die "Failed build/test with $resolver!"
done
echo "Success"