1

I am trying to construct an associative array in bash

#!/bin/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?

1
  • 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
    Commented Apr 22, 2014 at 23:18

2 Answers 2

3

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).

2
  • 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
    Commented Apr 22, 2014 at 18:42
  • 2
    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
    Commented Apr 22, 2014 at 18:43
0

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

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

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

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

Good luck!

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .