Passing associative array as argument with Bash [duplicate] Passing associative array as argument with Bash [duplicate] shell shell

Passing associative array as argument with Bash [duplicate]


you can use local -n for a reference

 declare -A weapons=( ['Straight Sword']=75 ['Tainted Dagger']=54 ['Imperial Sword']=90 ['Edged Shuriken']=25 )  print_weapons() {     local -n array=$1     for i in "${!array[@]}"; do         printf "%s\t%d\n" "$i" "${array[$i]}"     done }  print_weapons weapons


I don't think you can pass associative arrays as an argument to a function. You can use the following hack to get around the problem though:

#!/bin/bashdeclare -A weapons=(  ['Straight Sword']=75  ['Tainted Dagger']=54  ['Imperial Sword']=90  ['Edged Shuriken']=25)function print_array {    eval "declare -A arg_array="${1#*=}    for i in "${!arg_array[@]}"; do       printf "%s\t%s\n" "$i ==> ${arg_array[$i]}"    done}print_array "$(declare -p weapons)" 

Output

Imperial Sword ==> 90   Tainted Dagger ==> 54   Edged Shuriken ==> 25   Straight Sword ==> 75   


It's ugly enough using variable indirection with regular arrays, working with associative arrays is difficult -- I did not find a way to iterate over the keys.

I wonder if all you need is declare -p:

print_array() { declare -p $1; }print_array weapons
declare -A weapons='(["Imperial Sword"]="90" ["Tainted Dagger"]="54" ["Edged Shuriken"]="25" ["Straight Sword"]="75" )'

Or, prettier:

print_array() { declare -p $1 | sed 's/[[)]/\n&/g'; }print_array weapons
declare -A weapons='(["Imperial Sword"]="90" ["Tainted Dagger"]="54" ["Edged Shuriken"]="25" ["Straight Sword"]="75" )'