Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Associative arrays with space in the key

Tags:

arrays

bash

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?

like image 365
Bajji Avatar asked Apr 23 '13 18:04

Bajji


1 Answers

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.

like image 114
Alex Avatar answered Sep 24 '22 09:09

Alex