I'm trying to read the English dictionary in Linux into an associative array, using the words as keys and and predefined string as a value. This way I can look up words by key to see if they exist. Also I need all to words to be lowercase. It's fairly simple but the bash syntax is getting in my way. When I run the code below, I get a 'bad array subscript' error. Any thoughts as to why that might be ?
 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'
    }
                $index is empty at some point. You also have a rather totally pointless use of echo assuming you wanted the line verbatim and not whitespace compressed. Just use index="${line,,}".
I think following example will help..
$ declare -A colour
$ colour[elephant]="black"
$ echo ${colour[elephant]}
black
$ index=elephant
$ echo ${colour["$index"]}
black
                        To use associative arrays in bash, you need bash version 4, and you need to declare the array as an associative array with declare -A englishDictionaryArray
http://www.linuxjournal.com/content/bash-associative-arrays
Combining your work and other answers, try this:
I'm using GNU bash, version 4.2.37(1)-release (x86_64-pc-linux-gnu)
#!/bin/bash
declare -A DICT
function createDict(){
    while read LINE; do
        INDEX=${LINE,,}
        DICT[$INDEX]="exists"
    done < /usr/share/dict/words
}
createDict
echo ${DICT[hello]}
echo ${DICT[acdfg]}
echo ${DICT["a's"]}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With