theGrayFox theGrayFox - 1 year ago 150
Bash Question

Passing associative array as argument with Bash

What's the best way to pass an associative array as an argument to a function to avoid the repetition of having to iterate over numerous associate arrays? That way I can give the function any array of my choice to print. Here's what I have:

# Snippet

declare -A weapons=(
['Straight Sword']=75
['Tainted Dagger']=54
['Imperial Sword']=90
['Edged Shuriken']=25
)

print_weapons() {
for i in "${!weapons[@]}"; do
printf "%s\t%d\n" "$i" "${weapons[$i]}"
done
}

print_weapons

Answer Source

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/bash

declare -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   
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download