2

I wanted a hashmap equivalent in bash (keys as string and values as a list of integers). So, I wrote the following code-

declare -A PUBS

PUBS=( "FEE":"[345, 342]" "FOO":"[1, 2, 44]" "BAR":"[23, 67]" )

However, I get an error saying must use subscript when assigning associative array.

What's wrong here?

kev
  • 2,741
  • 5
  • 22
  • 48
  • Since `[345, 342]` isn't any kind of `bash` literal, you might as well dispense with the unnecessary brackets and comma and just write `PUBS=([FEE]="345 342" [FOO]="1 2 44" [BAR]="23 67")`. – chepner Mar 12 '19 at 22:06
  • Got it, but does it hurt to have it like that in the code? The main reason is that I want to pass all these values as a list parameter to a Python file. – kev Mar 12 '19 at 22:10
  • That would assume your Python program is using something like `eval` to create a list from a string argument, right? That's probably a bad idea. – chepner Mar 12 '19 at 22:23
  • @chepner Oh, what do you recommend then? How do I pass these values `[345, 342]`? And how do I parse them in my Python program to make a list? – kev Mar 12 '19 at 22:26
  • The simplest thing (assuming there are no other arguments), would be to pass each integer as a separate argument, and have Python collect them into a list itself. A proper treatment deserves its own question, though. – chepner Mar 12 '19 at 22:43
  • @chepner `ast.literal_eval()` is a fine way to parse something like this in Python. – Barmar Mar 13 '19 at 13:43

1 Answers1

6

You're not using the correct syntax to specify the keys. It's [key]=value, not key:value. So it should be:

PUBS=( ["FEE"]="[345, 342]" ["FOO"]="[1, 2, 44]" ["BAR"]="[23, 67]" )
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • a quick follow-up question- How do I loop through this hashmap? I want to get the keys and values for each iteration. – kev Mar 12 '19 at 21:51
  • 1
    https://stackoverflow.com/questions/3112687/how-to-iterate-over-associative-arrays-in-bash – Barmar Mar 12 '19 at 21:53