Associative arrays with a space in the key

I am trying to create an associative array in bash as follows

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

This outputs the desired result: Ashwin on execution.

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 spaces allowed in it?

+5
source share
1 answer

If you first use declare -A hashbefore assigning values, then the script works as expected.

Tested using bash 4.2.25

+9
source

All Articles