Associative arrays are local by default

Fine, 4.2 adds "declare -g" but it's buggy for associative arrays so it doesn't (yet) answer the question. Here's my bug report and Chet's confirmation that there's a fix scheduled for the next release.

http://lists.gnu.org/archive/html/bug-bash/2013-09/msg00025.html

But I've serendipitously found a workaround, instead of declaring the array and assigning an initial value to it at the same time, first declare the array and then do the assignment. That is, don't do this:

declare -gA a=([x]=1 [y]=2)

but this instead:

declare -gA a; a=([x]=1 [y]=2)

From: Greg Wooledge
Sent: Tue, 23 Aug 2011 06:53:27 -0700
Subject: Re: YAQAGV (Yet Another Question About Global Variables)

bash 4.2 adds "declare -g" to create global variables from within a function.

Thank you Greg! However Debian Squeeze still has Bash 4.1.5


You have already answered your own question with declare -g. The workaround on bash versions < 4.2 is to declare the array outside of the function.

f() {
   map[y] = foo
}

declare -A map
foo
echo "${map[y]}"

Tags:

Bash

Scope