How to pass an associative array as argument to a function in Bash?
arrays, associative, associative-array, bash
Solution
If you're using Bash 4.3 or newer, the cleanest way is to pass the associative array by name reference and then access it inside your function using a name reference with `local -n`. For example:
function foo {
local -n data_ref=$1
echo ${data_ref[a]} ${data_ref[b]}
}
declare -A data
data[a]="Fred Flintstone"
data[b]="Barney Rubble"
foo data
You don't have to use the `_ref` suffix; that's just what I picked here. You can call the reference anything you want so long as it's different from the original variable name (otherwise youll get a "circular name reference" error).
Problem
How do you pass an associative array as an argument to a function? Is this possible in Bash? The code below is not working as expected: ``` function iterateArray { local ADATA="${@}" # associative array for key in "${!ADATA[@]}" do echo "key - ${key}" echo "value: ${ADATA[$key]}" done } ``` Passing associative arrays to a function like normal arrays does not work: ``` iterateArray "$A_DATA" ``` or ``` iterateArray "$A_DATA[@]" ```