Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

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 at 23:18

1 Answer 1

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 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 Apr 22 at 18:43

Your Answer

 
discard

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.