Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am trying to construct an associative array in bash

declare -A hero_escore

    hero_escore=( "Invoker_Anti-Mage : -44"
    "Tinker_Nyx Assassin : 32"
    "Troll Warlord_Drow Ranger : 3" )

These are 3 different lines. It is intended to be like that only. But the above code gives an error for each line - Troll Warlord_Drow Ranger : 3: must use subscript when assigning associative array. Is it because it is expecting me to use something like this - [Invoker_Anti-Mage]="-44"? If so is there anyway I can make it work the way I have used in my program using bash 3 or something? I want to construct an associative array with the format that I have given. Is it possible?

share|improve this question
If you are trying to program a game in bash for the sake of making things hard on yourself, rock on. If you are just trying to program a game, bash is a very poor choice of language for the task. – msw Apr 22 '14 at 23:18

If you want an associative array, you'll have to use bash 4 and use the syntax it expects. The code you show would simply assign three strings to an indexed array (if here_escore had not been declared as an associative array).

share|improve this answer
hero_escore has been declared as an associative array. But I get the error that I have mentioned in the question. Is there any way by which I can use something like this ${hero_escore["Troll Warlord_Drow Ranger"] to retrieve the value "3" with the existing code? Bash 4 or not. I can make other changes if I have to user bash 3. – Ashwin Apr 22 '14 at 18:42
I know. That's why your assignment fails. You need to use the correct syntax for assigning to an associative array, which is foo=([key1]=value1 [key2]=value2), or foo[key]=value. – chepner Apr 22 '14 at 18:43

I think this solution should work for you in Bash 4:

declare -A hero_escore=( ["Invoker_Anti-Mage"]="-44"
    ["Troll-Warlord_Drow-Ranger"]="3" )

for hero in ${!hero_escore[@]}; do
    echo "$hero : ${hero_escore[$hero]}";

I also found this post really helpful: http://stackoverflow.com/questions/1494178/how-to-define-hash-tables-in-bash

Good luck!

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.