Issue
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
Solution
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
Answered By - jaypal singh