koalaman / shellcheck

ShellCheck, a static analysis tool for shell scripts
https://www.shellcheck.net
GNU General Public License v3.0
36.44k stars 1.78k forks source link

False positive: SC2190 Elements in associative arrays need index #2393

Open wolfaba opened 2 years ago

wolfaba commented 2 years ago

For bugs

For new checks and feature suggestions

Here's a snippet or screenshot that shows the problem:


#!/usr/bin/env bash

declare -A q

q=( "k1" "v1" "k2" "v2")

echo "${q[k1]}"

Here's what shellcheck currently says:

Line 5:
q=( "k1" "v1" "k2" "v2")
    ^-- SC2190 (warning): Elements in associative arrays need index, e.g. array=( [index]=value ) .
         ^-- SC2190 (warning): Elements in associative arrays need index, e.g. array=( [index]=value ) .
              ^-- SC2190 (warning): Elements in associative arrays need index, e.g. array=( [index]=value ) .
                   ^-- SC2190 (warning): Elements in associative arrays need index, e.g. array=( [index]=value ) .

Here's what I wanted or expected to see:

Code OK

Bash man page says

When assigning to an associative array, the words in a compound assignment may be either assignment statements, for which the subscript is required, or a list of words that is interpreted as a sequence of alternating keys and values: name=( key1 value1 key2 value2 ...). These are treated identically to name=( [key1]=value1 [key2]=value2 ...). The first word in the list determines how the remaining words are interpreted; all assignments in a list must be of the same type. When using key/value pairs, the keys may not be missing or empty; a final missing value is treated like the empty string.

It means the syntax var=( key val key val ) is valid.

Please, update the code and the wiki page https://github.com/koalaman/shellcheck/wiki/SC2190

Thank you.

Regards.

Robert.

chreekat commented 8 months ago

It looks like the ability to use a list of key-values was added in bash 5.1: https://git.savannah.gnu.org/cgit/bash.git/tree/NEWS#n273

Is there a way to guard the check on shell version?