Search code examples
arraysbashpass-by-referenceassociative-array

How to use a bash variable reference to an associative array in a bash function without declaring it before calling that function?


There are multiple ways to get a result from a function in a bash script, one is to use reference variables like local -n out_ref="$1, which is also my preferred way.

My bash version is:

GNU bash, Version 5.0.3(1)-release 

Recently, one of my bash functions needed to produce a associative array as a result, like in this example code:

#!/bin/bash

testFunction() {
    local -n out_ref="$1"

    out_ref[name]="Fry"
    out_ref[company]="Planet Express"
}

declare -A employee
testFunction employee

echo -e "employee[name]: ${employee[name]}"
echo -e "employee[company]: ${employee[company]}"

I declare the variable employee as an associative array with declare -A.

The output is:

employee[name]: Fry
employee[company]: Planet Express

If I remove the line declare -A employee, the output is:

employee[name]: Planet Express
employee[company]: Planet Express

Is there a way to move the declaration of the associative array into the function, so the user of that function does not need to do it beforehand?


Solution

  • Use declare -Ag "$1" inside the function, so that you declare employee as a global variable.