Alberto
Alberto

Reputation: 1489

Get value from array of dictionaries bash

I'm learning how bash scripting and I need to know how to get a value from an array of dictionaries. I did this for the declaration:

declare -a persons
declare -A person
person[name]="Bob"
person[id]=12
persons[0]=$person

If I do the following it works fine:

echo ${person[name]}
# Bob

But when I try to access to the values from the array it doesn't work. I tried these options:

echo ${persons[0]}
# empty result
echo ${persons[0][name]}
# empty result
echo persons[0]["name"]
# persons[0][name]
echo ${${persons[0]}[name]} #It could have worked if this work as a return
# Error

And I dont know what more try. Any help would be appreciated!

Thank you for reading!

Bash version: 4.3.48

Upvotes: 0

Views: 2816

Answers (1)

sjsam
sjsam

Reputation: 21965

The notion of a multi-dimensional array is not supported in bash, So

${persons[0][name]}

will not work. However, from Bash 4.0, bash has associative arrays, which you seemed to have tried, which suits your test case. For example you may do it like below:

#!/bin/bash
declare -A persons
# now, populate the values in [id]=name format
persons=([1]="Bob Marley" [2]="Taylor Swift" [3]="Kimbra Gotye")
# To search for a particular name using an id pass thru the keys(here ids) of the array using the for-loop below

# To search for name using IDS

read -p "Enter ID to search for : " id
re='^[0-9]+$'
if ! [[ $id =~ $re ]] 
then
 echo "ID should be a number"
 exit 1
fi
for i in ${!persons[@]} # Note the ! in the beginning gives you the keys
do
if [ "$i" -eq "$id" ]
then
  echo "Name : ${persons[$i]}"
fi
done
# To search for IDS using names
read -p "Enter  name to search for : " name
for i in "${persons[@]}" # No ! here so we are iterating thru values
do
if [[ $i =~ $name ]] # Doing a regex match
then
  echo "Key : ${!persons[$i]}" # Here use the ! again to get the key corresponding to $i
fi
done

Upvotes: 1

Related Questions