From d625116ea90bc2655338fecf765406315a6e0aaf Mon Sep 17 00:00:00 2001 From: Sietse Brouwer Date: Mon, 21 Nov 2022 14:38:26 +0100 Subject: [PATCH] Hint at loop variables' concrete values: name them `v` (for value) or `k` (for key) --- SC2302.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/SC2302.md b/SC2302.md index 937c93c..7dbb721 100644 --- a/SC2302.md +++ b/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: