shellcheck icon indicating copy to clipboard operation
shellcheck copied to clipboard

SC2178/SC2128 false positives on local variables

Open knirch opened this issue 9 years ago • 4 comments

#!/bin/bash

foo () {
   local baz=()
   echo "${baz[@]}"
}

bar () {
   local baz=""
   # Variable was used as an array but is now assigned a string. [SC2178]
   echo "$baz"
   # Expanding an array without an index only gives the first element. [SC2128]
}

knirch avatar May 29 '16 11:05 knirch

Saw the mention on the SC2178 page. Close if you want to, not too much refactoring needed to work around this.

knirch avatar May 29 '16 11:05 knirch

Unsure if things have changed, but whilst clearing up old warnings I noticed that the above code can be fixed by simply changing local baz="" to local baz

#!/bin/bash

foo () {
   local baz=()
   echo "${baz[@]}"
}

bar () {
   local baz
   echo "$baz"
}

knirch avatar Oct 15 '18 12:10 knirch

@knirch Thanks for describing that workaround, I updated the wiki to include it: SC2128, SC2178

b0o avatar Feb 10 '20 01:02 b0o

Also functions defined using outer parens rather than braces like:

do-it() (
  foo=(xyz)
)

do-also() (
  foo=xyz
)

should not trigger these warnings.

I use parens for defining functions as much as possible as it limits global side-effects. Vars defined within are essentially "local".

ingydotnet avatar Aug 12 '22 15:08 ingydotnet