44

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?

1
  • note to self: PKGBUILDs need associative arrays to be global to be readable inside package_pkgname functions. Commented Jun 14, 2022 at 23:32

5 Answers 5

37

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

0
10

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)
8

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]}"
2
  • 2
    That option is explicitly shown in my own example. It doesn't work, however, when you need to 'unset' and then 'declare' the same variable inside a function. But still, a workaround exists for Bash < 4.2 and consists in 'echo'ing the variable declaration from inside the function to an external 'eval' with access to the main environment.
    – davide
    Commented May 29, 2012 at 22:04
  • i have this same scenario, but im declaring it on top of the function (as opposed to under like you did) but having problems with it not resetting(via functions commands), will that work declaring it on top of the function, then setting the function, then calling it later several times to have it reset? or does it need to be declared after the function? and where to you call your function f in your example? thats confusing. or did you mean f instead of foo below your declare?
    – blamb
    Commented Sep 15, 2023 at 16:12
6

Just to have a complete and runnable example.

One function creates a global associative array variable inside itself.
Other function assigns a value to the array variable.

bash 4.2 and above

set -euf +x -o pipefail # There is no place for implicit errors in this script.

function init_arrays(){
    # FYI. Multiple array declarations are not a problem. You can invoke it multiple times.

    # The "-gA" switch is the trick for the global array declaration inside a function.
    declare -gA my_var
}

function do_work(){
    init_arrays

    my_var[$1]=OPPA
}

do_work some_key

echo ${my_var[some_key]}
echo It is expected to get OPPA value printed above

Tested over GNU bash, version 4.4...

macOS

bash on macOS has 3.2 version (02/2023).
You have to use zsh, if you remove comments from the above init_arrays function.

function init_arrays(){
    declare -gA my_var
}

function do_work(){
    init_arrays
    my_var[$1]=OPPA
}

do_work some_key; echo ${my_var[some_key]}

Important notes

(bash) The declare -A command doesn't actually create an associative array immediately; it just sets an attribute on a variable name which allows you to assign to the name as an associative array. The array itself doesn't exist until the first assignment (!!!).

1
  • 1
    That -gA trick is gold, i can't believe this is the only place I've seen it. Commented Feb 28, 2023 at 19:29
0

For those who are stuck with Bash version < 4.2 and are not comfortable with proposed workarounds I share my custom implementation of global associative arrays. It does not have the full power of bash associative arrays and you need to be careful about special characters in array index, but gets job done.

get_array(){
   local arr_name="$1"
   local arr_key="$2"

   arr_namekey_var="ASSOCARRAY__${arr_name}__${arr_key}"
   echo "${!arr_namekey_var:=}"
}

set_array(){
   local arr_name="$1"
   local arr_key="$2"
   local arr_value="$3"

   arr_namekey_var="ASSOCARRAY__${arr_name}__${arr_key}"
   if [[ -z "${arr_value}" ]]; then
      eval ${arr_namekey_var}=
   else
      printf -v "${arr_namekey_var}" "${arr_value}"
   fi
}

Few notes:

  • Array name and array key could be combined into a single value, but split proved convenient in practice.
  • __ as a separator can by hacked by malicious or careless use -- to be on the safe side use only single-underscore values in array name and key, on top of only using alphanumeric values. Of course the composition of the internal variable (separators, prefix, suffix...) can be adjusted to application and developer needs.
  • The default value expansion guarantees that undefined array key (and also array name!) will expand to null string.
  • Once you move to version of bash where you are comfortable with builtin associative arrays, these two procedures can be used as wrappers for actual associative arrays without having to refactor whole code base.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.