Bash: Incorrect automated feedback "$/${} is unnecessary on arithmetic variables" from key of associative array

The automated feedback system for bash incorrectly says “$/${} is unnecessary on arithmetic variables” when using an associative array in an arithmetic context. In the following example, removing the $ breaks the code:

readonly -A CHAR_VALUES=(["+"]=1 ["-"]=2 ["|"]=3)
(( rows[row_num] += 4 ** col_num * CHAR_VALUES[$char] ))

The full code that produced this error is here, if needed for reference.

1 Like

CHAR_VALUES is used in an arithmetic context so (( ${CHAR_VALUES[$char]} )) can be written (( CHAR_VALUES[$char] )). However, since CHAR_VALUES is an associative array, the [...] isn’t an arithmetic context and $ is needed for $char.

This is bash v5.2

char='-'
row_num=3
col_num=4

readonly -A CHAR_VALUES=(["+"]=1 ["-"]=2 ["|"]=3)
(( rows[row_num] += 4 ** col_num * CHAR_VALUES[$char] ))

declare -p rows
# => declare -a rows=([3]="512")

However, yes, you get that finding.
We use shellcheck for the automated feedback, and it (erroneously) produces that warning.

$ shellcheck /tmp/rectangles.bash

In /tmp/rectangles.bash line 9:
        (( rows[row_num] += 4 ** col_num * CHAR_VALUES[$char] ))
                                                       ^---^ SC2004 (style): $/${} is unnecessary on arithmetic variables.

I suppose that while shellcheck is parsing that line, it doesn’t know that CHAR_VALUES is an associative array

You could always file a bug report