Hint at loop variables' concrete values: name them v (for value) or k (for key)

Sietse Brouwer
2022-11-21 14:38:26 +01:00
parent e62b5b3820
commit d625116ea9

@@ -6,9 +6,9 @@ Plus companion warning [[SC2303]]: `i is an array value, not a key. Use directly
```sh ```sh
array=(foo bar) array=(foo bar)
for i in "${array[@]}" for v in "${array[@]}"
do do
echo "Value is ${array[$i]}" echo "Value is ${array[$v]}"
done done
``` ```
@@ -17,19 +17,19 @@ done
Either loop over values Either loop over values
```sh ```sh
for i in "${array[@]}" for v in "${array[@]}"
do do
echo "Value is $i" echo "Value is $v"
done done
``` ```
or loop over keys: or loop over keys:
```sh ```sh
for i in "${!array[@]}" for k in "${!array[@]}" # Note `!`
do do
echo "Key is $i" echo "Key is $k"
echo "Value is ${array[$i]}" echo "Value is ${array[$k]}"
done done
``` ```
@@ -37,11 +37,11 @@ done
ShellCheck found a `for` loop over array *values*, where the variable is used as an array *key*. 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: ### Exceptions: