Pattern: Use of for
loop over array values
Issue: -
ShellCheck found a for
loop over array values, where the variable is used as an array key.
In the problematic example, the loop will print Value is foo
twice. On the second iteration, i=bar
, and bar
is unset and considered zero, so ${array[$i]}
becomes ${array[bar]}
becomes ${array[0]}
becomes foo
.
If you don't care about the key, simply loop over array values and use $i
to refer to the array value, like in the first correct example.
If you do want the key, loop over array keys with "${!array[@]}"
, use $i
to refer to the array key, and ${array[$i]}
to refer to the array value.
Example of incorrect code:
array=(foo bar)
for i in "${array[@]}"
do
echo "Value is ${array[$i]}"
done
Example of correct code:
for i in "${array[@]}"
do
echo "Value is $i"
done