2

When I run the following shell script always I am getting the output as "grault" for any key. What would be the problem?

thanks!

#!/bin/bash

declare -a MYMAP                             
MYMAP=( [foo]=bar [baz]=quux [corge]=grault ) 

echo ${MYMAP[foo]}

echo ${MYMAP[baz]}
Cyrus
  • 84,225
  • 14
  • 89
  • 153
G G
  • 1,049
  • 4
  • 17
  • 26

2 Answers2

3

Create an associative array with -A:

declare -A MYMAP

See: help declare

Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • I am getting following error with -A associate-array.bash: line 2: declare: -A: invalid option declare: usage: declare [-afFirtx] [-p] [name[=value] ...] – G G Aug 13 '15 at 19:48
  • 1
    Sorry, your bash has no option `-A`. Add output of `echo $BASH_VERSION` – Cyrus Aug 13 '15 at 19:50
  • 2
    @GG You are probably on a Mac. Associative arrays were added in version 4. – John1024 Aug 13 '15 at 19:53
  • @GG: Take a look at [Create associative array in bash 3](http://stackoverflow.com/questions/11776468/create-associative-array-in-bash-3) – Cyrus Aug 13 '15 at 19:58
  • 1
    @GG Your welcome, of course, but it was Cyrus who correctly identified the issues. To thank him, I suggest that you accept and upvote his answer. For more information of Stackoverflow's peculiar customs, see: [What should I do when someone answers my question?](http://stackoverflow.com/help/someone-answer) – John1024 Aug 13 '15 at 20:39
1

The other answer describes how to do it right, but here's the explanation of why your example behaves as it does.

declare -a creates an indexed array, which should only accept integers for the index. If you provide a string as the index, it will just disregard it and treat it as a 0! (I think this is a poor behavior, it should just give an error).

So this is what your code translated to:

declare -a MYMAP # create indexed array                           
MYMAP=( [0]=bar [0]=quux [0]=grault ) 

echo ${MYMAP[0]} # grault

echo ${MYMAP[0]} # grault
wisbucky
  • 33,218
  • 10
  • 150
  • 101