8

I am trying to create an associative array in Bash in the following way:

#!/bin/bash
hash["name"]='Ashwin'
echo ${hash["name"]}

This prints the desired output, Ashwin, when executed.

But when the key has a space in it,

#!/bin/bash
hash["first name"]='Ashwin'
echo ${hash["first name"]}

I get the following error

test2.sh: line 2: first name: syntax error in expression (error token is "name")

Are keys not allowed to have spaces in them?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Bajji
  • 2,243
  • 2
  • 22
  • 35
  • 3
    Based on your comment to the answer you are using bash 3. Bash 3 does not support associative arrays, here are some [workarounds](http://stackoverflow.com/questions/11776468/create-associative-array-in-bash-3) – iruvar Apr 23 '13 at 19:23
  • 3
    Since associative arrays aren't supported prior to `bash` 4, your first example is actually being treated as a regular array. The parser is able to deal with simple strings where it expects an integer value, and treats them all as having the value 0. You can index `hash` with many different strings and `${hash[key]}` still expands to `Ashwin`. – chepner Apr 23 '13 at 20:12

1 Answers1

12

If you first use declare -A hash before the value assignments, then the script runs as expected.

It was tested using Bash 4.2.25.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Alex
  • 10,470
  • 8
  • 40
  • 62