shellcheck
shellcheck copied to clipboard
SC2178/SC2128 false positives on local variables
#!/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]
}
Saw the mention on the SC2178 page. Close if you want to, not too much refactoring needed to work around this.
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"
}
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".