-
Notifications
You must be signed in to change notification settings - Fork 1.9k
SC2128
myarray=(foo bar)
for f in $myarray
do
cat "$f"
donemyarray=(foo bar)
for f in "${myarray[@]}"
do
cat "$f"
doneWhen referencing arrays, $myarray is equivalent to ${myarray[0]} -- it results in only the first of multiple elements.
To get all elements as separate parameters, use the index @ (and make sure to double quote). In the example, echo "${myarray[@]}" is equivalent to echo "foo" "bar".
To get all elements as a single parameter, concatenated by the first character in IFS, use the index *. In the example, echo "${myarray[*]}" is equivalent to echo "foo bar".
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:
foo () {
local -a baz
baz+=("foo" "bar")
echo "${baz[@]}"
}
bar () {
local baz="qux"
echo "$baz"
}Correct Code:
foo () {
local -a baz
baz+=("foo" "bar")
echo "${baz[@]}"
}
bar () {
local baz
baz="qux"
echo "$baz"
}