Associative arrays are local by default

bash, scope

Solution

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

Problem

Associative arrays seem to be local by default when declared inside a function body, where they should be global. The following code ``` #!/bin/bash f() { declare -A map map[x]=a map[y]=b } f echo x: ${map[x]} y: ${map[y]} ``` produces the output: ``` x: y: ``` while this ``` #!/bin/bash declare -A map f() { map[x]=a map[y]=b } f echo x: ${map[x]} y: ${map[y]} ``` produces the output: ``` x: a y: b ``` Is it possible to declare a global associative array within a function? Or what work-around can be used?

Original source

Related problems