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?
Some DB systems natively store associative arrays by serializing the data and then storing that serialized data and the key. Individual arrays can then be loaded or saved from the database using the key to refer to them.
An associative array data type is a data type used to represent a generalized array with no predefined cardinality. Associative arrays contain an ordered set of zero or more elements of the same data type, where each element is ordered by and can be referenced by an index value.
When an array is declared locally, then it always initializes in the stack memory, and generally, stack memory has a size limit of around 8 MB. This size can vary according to different computer architecture. When an array is declared globally then it stores in the data segment, and the data segment has no size limit.
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With