Shashwat Kumar
Shashwat Kumar

Reputation: 5297

Bash map not giving proper result

I am using map in bash as follows:

declare -a hash
hash=(["a"]="A" ["b"]="B" ["c"]="C" ["d"]="D")

echo ${hash["a"]}

https://ideone.com/YfnazQ

However it is printing D instead of A. What's is the issue in this snippet?

Upvotes: 1

Views: 270

Answers (2)

TheCaronte
TheCaronte

Reputation: 96

Your problem is just how you defined the variable hash.

declare -a hash is for indexed arrays, I mean, arrays where the index is just numbers.

To declare an associative array, just change -a for -A:

declare -A hash

That way you can write letters as the index, and that echo will work as expected.

Hope I helped!

Upvotes: 1

oklas
oklas

Reputation: 8220

You have mistake or typo, you specified key -a instead of -A

So instead:

declare -a hash

use:

declare -A hash

Upvotes: 0

Related Questions