Skip to content

Commit

Permalink
SC2321: Warn about redundant $(()) in arr[$((i))]=x (ref: koalaman#1666)
Browse files Browse the repository at this point in the history
  • Loading branch information
koalaman committed Jul 24, 2022
1 parent d1d574c commit 30bb0e0
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
- SC2317: Warn about unreachable commands
- SC2318: Warn about backreferences in 'declare x=1 y=$x'
- SC2319/SC2320: Warn when $? refers to echo/printf/[ ]/[[ ]]/test
- SC2321: Suggest removing $((..)) in array[$((idx))]=val

### Fixed
- SC2086: Now uses DFA to make more accurate predictions about values
Expand Down
18 changes: 18 additions & 0 deletions src/ShellCheck/Analytics.hs
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,7 @@ nodeChecks = [
,checkCommandIsUnreachable
,checkSpacefulnessCfg
,checkOverwrittenExitCode
,checkUnnecessaryArithmeticExpansionIndex
]

optionalChecks = map fst optionalTreeChecks
Expand Down Expand Up @@ -4913,5 +4914,22 @@ checkOverwrittenExitCode params t =
_ -> False


prop_checkUnnecessaryArithmeticExpansionIndex1 = verify checkUnnecessaryArithmeticExpansionIndex "a[$((1+1))]=n"
prop_checkUnnecessaryArithmeticExpansionIndex2 = verifyNot checkUnnecessaryArithmeticExpansionIndex "a[1+1]=n"
prop_checkUnnecessaryArithmeticExpansionIndex3 = verifyNot checkUnnecessaryArithmeticExpansionIndex "a[$(echo $((1+1)))]=n"
checkUnnecessaryArithmeticExpansionIndex params t =
case t of
T_Assignment _ mode var [TA_Sequence _ [ TA_Expansion _ [expansion@(T_DollarArithmetic id _)]]] val ->
styleWithFix id 2321 "Array indices are already arithmetic contexts. Prefer removing the $(( and ))." $ fix id
_ -> return ()

where
fix id =
fixWith [
replaceStart id params 3 "", -- Remove "$(("
replaceEnd id params 2 "" -- Remove "))"
]


return []
runTests = $( [| $(forAllProperties) (quickCheckWithResult (stdArgs { maxSuccess = 1 }) ) |])

0 comments on commit 30bb0e0

Please sign in to comment.