Bajji
Bajji

Reputation: 2393

Associative arrays with space in the key

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?

Upvotes: 8

Views: 2850

Answers (1)

Alex
Alex

Reputation: 11090

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.

Upvotes: 12

Related Questions