在bash关联数组中使用变量作为键

Asg*_*eir 5 linux syntax bash associative-array

我正在尝试将Linux中的英语词典读为一个关联数组,使用单词作为键并将预定义的字符串用作值。这样,我可以按关键字查找单词以查看它们是否存在。我还需要所有单词都小写。这很简单,但是bash语法妨碍了我。当我运行下面的代码时,出现“错误数组下标”错误。有什么想法为什么呢?

 function createArrayFromEnglishDictionary(){
        IFS=$'\n'
        while read -d $'\n' line; do
            #Read string into variable and put into lowercase.
            index=`echo ${line,,}`
            englishDictionaryArray[$index]="exists"
            done < /usr/share/dict/words
            IFS=$' \t\n'
    }
Run Code Online (Sandbox Code Playgroud)

Job*_*bin 6

我认为下面的例子会有所帮助..

$ declare -A colour
$ colour[elephant]="black"
$ echo ${colour[elephant]}
black

$ index=elephant
$ echo ${colour["$index"]}
black
Run Code Online (Sandbox Code Playgroud)


jør*_*sen 5

$index在某个时候是空的。假设您要逐行而不是空白压缩,则对回波的使用完全没有意义。只需使用index="${line,,}"