Passing associative array as argument with Bash

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

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published