Update
As multiple comments have pointed out, associative arrays are not available / supported in Bash 2 or Bash 3. Closing this thread. See below for how we solved the Problem that we were trying to solve using Associative Arrays.
Problem
We have a Project where a Bash Associative Array is declared in a File, say def.sh, like so
#!/bin/bash
declare -a map=(
["Key_A"]='Val_A'
["Key_B"]='VAL_B'
)
This File is sourced on Terminal with source def.sh, and then individual elements are accessed like so
export var_a="xyz"
var_b="${map[${var_a}]}"
Reason why this is done this way has something to do with the in-house Systems that we are working with and requirements of Project.
This was working fine earlier when the Map had only one entry.
When we added a second entry to the map (i.e. when it looks like snippet above), this map always returns the value of second / last entry / pair.
That is, even if we do
export var_a="Key_A"
var_b="${map[${var_a}]}"
echo ${var_b} gives VAL_B. Needless to say, "${map[KEY_B]}" still gives VAL_B.
We have tried without Parameter substitutions (i.e. "${map[KEY_A]}") with and without quotes, result is same.
Any idea on why this might be happening?
Edit :
For
Have tried with declare -A map=( as well, result is
bash: declare: -A: invalid option
declare: usage: declare [-afFirtx] [-p] [name[=value] ...]
help declare output :
declare: declare [-afFirtx] [-p] [name[=value] ...]
Declare variables and/or give them attributes. If no NAMEs are
given, then display the values of variables instead. The -p option
will display the attributes and values of each NAME.
The flags are:
-a to make NAMEs arrays (if supported)
-f to select from among function names only
-F to display function names (and line number and source file name if
debugging) without definitions
-i to make NAMEs have the `integer' attribute
-r to make NAMEs readonly
-t to make NAMEs have the `trace' attribute
-x to make NAMEs export
Variables with the integer attribute have arithmetic evaluation (see
`let') done when the variable is assigned to.
declare -A, bash array is indexed by integers. Thendeclare -a map=( ["Key_A"]='Val_A' ["Key_B"]='VAL_B' )is equivalent todeclare -a map=( [0]='Val_A' [0]='VAL_B' ). That is why the last value only remains. You'll need to modify the code to use integers as index (as far as you stick to bash 2 or 3).