How to pass an associative array as argument to a function in Bash?
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:
function print_array { # eval string into a new associative array eval "declare -A func_assoc_array="${1#*=} # proof that array was successfully created declare -p func_assoc_array}# declare an associative arraydeclare -A assoc_array=(["key1"]="value1" ["key2"]="value2")# show associative array definitiondeclare -p assoc_array# pass associative array in string form to functionprint_array "$(declare -p assoc_array)"
If you're using Bash 4.3 or newer, the cleanest way is to pass the associative array by name 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 datadata[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).
Based on Florian Feldhaus's solution:
# Bash 4+ onlyfunction printAssocArray # ( assocArrayName ) { var=$(declare -p "$1") eval "declare -A _arr="${var#*=} for k in "${!_arr[@]}"; do echo "$k: ${_arr[$k]}" done}declare -A confconf[pou]=789conf[mail]="ab\npo"conf[doo]=456printAssocArray "conf"
The output will be:
doo: 456pou: 789mail: ab\npo