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[@]"
From the best Bash guide ever:
I think the issue in your case is that
$@
is not an associative array: "@: Expands to all the words of all the positional parameters. If double quoted, it expands to a list of all the positional parameters as individual words."Update, to fully answer the question, here is an small section from my library:
Iterating an associative array by reference
This we a devlopment of my earlier work, which I will leave below.
@ffeldhaus - nice response, I took it and ran with it:
Here is a solution I came up with today using
eval echo ...
to do the indirection:Outputs on bash 4.3:
Based on Florian Feldhaus's solution:
The output will be:
I had exactly the same problem last week and thought about it for quite a while.
It seems, that associative arrays can't be serialized or copied. There's a good Bash FAQ entry to associative arrays which explains them in detail. The last section gave me the following idea which works for me:
You can only pass associative arrays by name.
It's better (more efficient) to pass regular arrays by name also.