How to pass a Map Data Structure as an argument to a method in a Bash Script

I want to create a data structure Person like a Map and want to pass it to a function in bash script. In the method I want to retrieve “Person” like Person[Name] ,Person[Age] , Person [Dept] as Mark , 10 and Finance respectively. etc. But I am not able to get and getting the output as mentioned in the comment. Need some guidance here how to that or what I am doing wrong.

Here is the script

#!/bin/bash -e
getValue(){
    local Person=$1
    echo Person[Name]
}

Person[Name]=”Mark”
Person [Age]=”10”
Person [Dept]=”Finance”
echo ${Person[Name]}   # why is  it printing Finance.I am expecting it to be printed as Mark   

getValue Person               # output is coming as Person
getValue ${Person}         # output is coming as  Finance
getValue  ${Person[@]} # output is coming as  Finance

Upvotes: 5

Views: 2529

Answers (1)

utpal416
utpal416

Reputation: 927

You have to define Person as an associative array. Here is the running code if you are using bash version 4 or above.

#!/bin/bash -e
function getValue(){
        person=$(declare -p "$1")
        declare -A person_arr=${person#*=}
        echo ${person_arr[Name]} 
        echo ${person_arr[Age]} 
        echo ${person_arr[Dept]} 
}

declare -A Person
Person[Name]="X"
Person[Age]=10
Person[Dept]="Finance"
echo ${Person[Name]}  
echo ${Person[Age]}  
echo ${Person[Dept]} 
getValue "Person"

Upvotes: 5

Related Questions