mirror of
https://github.com/koalaman/shellcheck.git
synced 2025-10-03 19:29:44 +08:00
Hint at loop variables' concrete values: name them v
(for value) or k
(for key)
20
SC2302.md
20
SC2302.md
@@ -6,9 +6,9 @@ Plus companion warning [[SC2303]]: `i is an array value, not a key. Use directly
|
||||
|
||||
```sh
|
||||
array=(foo bar)
|
||||
for i in "${array[@]}"
|
||||
for v in "${array[@]}"
|
||||
do
|
||||
echo "Value is ${array[$i]}"
|
||||
echo "Value is ${array[$v]}"
|
||||
done
|
||||
```
|
||||
|
||||
@@ -17,19 +17,19 @@ done
|
||||
Either loop over values
|
||||
|
||||
```sh
|
||||
for i in "${array[@]}"
|
||||
for v in "${array[@]}"
|
||||
do
|
||||
echo "Value is $i"
|
||||
echo "Value is $v"
|
||||
done
|
||||
```
|
||||
|
||||
or loop over keys:
|
||||
|
||||
```sh
|
||||
for i in "${!array[@]}"
|
||||
for k in "${!array[@]}" # Note `!`
|
||||
do
|
||||
echo "Key is $i"
|
||||
echo "Value is ${array[$i]}"
|
||||
echo "Key is $k"
|
||||
echo "Value is ${array[$k]}"
|
||||
done
|
||||
```
|
||||
|
||||
@@ -37,11 +37,11 @@ done
|
||||
|
||||
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`.
|
||||
In the problematic example, the loop will print `Value is foo` twice. On the second iteration, `v=bar`, and `bar` is unset and considered zero, so `${array[$v]}` 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 don't care about the key, simply loop over array values and use `$v` 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.
|
||||
If you do want the key, loop over array keys with `"${!array[@]}"`, use `$k` to refer to the array key, and `${array[$k]}` to refer to the array value.
|
||||
|
||||
### Exceptions:
|
||||
|
||||
|
Reference in New Issue
Block a user