Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Associative arrays are local by default

Tags:

scope

bash

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?

like image 476
davide Avatar asked May 29 '12 20:05

davide


People also ask

How are associative arrays stored in memory?

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.

What type of data is stored in associative array?

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.

What is global and local array?

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.


2 Answers

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

like image 190
davide Avatar answered Sep 22 '22 21:09

davide


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) 
like image 36
memeplex Avatar answered Sep 23 '22 21:09

memeplex