mirror of
https://github.com/koalaman/shellcheck.git
synced 2025-10-03 19:29:44 +08:00
describe workaround to local variable confusion
33
SC2128.md
33
SC2128.md
@@ -30,4 +30,35 @@ To get all elements as a single parameter, concatenated by the first character i
|
|||||||
|
|
||||||
### Exceptions
|
### Exceptions
|
||||||
|
|
||||||
None.
|
ShellCheck can get confused by variable scope if the same variable name was used as an array previously, but is a string in the current context. You can [[ignore]] it in this case.
|
||||||
|
|
||||||
|
In the case of local variables, a workaround is to declare the local variable separately from assigning to it:
|
||||||
|
|
||||||
|
**Problematic Code:**
|
||||||
|
```sh
|
||||||
|
foo () {
|
||||||
|
local -a baz
|
||||||
|
baz+=("foo" "bar")
|
||||||
|
echo "${baz[@]}"
|
||||||
|
}
|
||||||
|
|
||||||
|
bar () {
|
||||||
|
local baz="qux"
|
||||||
|
echo "$baz"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct Code:**
|
||||||
|
```sh
|
||||||
|
foo () {
|
||||||
|
local -a baz
|
||||||
|
baz+=("foo" "bar")
|
||||||
|
echo "${baz[@]}"
|
||||||
|
}
|
||||||
|
|
||||||
|
bar () {
|
||||||
|
local baz
|
||||||
|
baz="qux"
|
||||||
|
echo "$baz"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
Reference in New Issue
Block a user