从字典数组中获取价值

时间:2017-06-22 10:21:28

标签: bash

我正在学习如何使用bash脚本编写,我需要知道如何从一组字典中获取值。我为宣言做了这个:

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

如果我执行以下操作,则可以正常工作:

echo ${person[name]}
# Bob

但是当我尝试访问数组中的值时,它不起作用。我尝试了这些选项:

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

我不知道还有什么尝试。任何帮助将不胜感激!

感谢您阅读!

Bash版本:4.3.48

1 个答案:

答案 0 :(得分:1)

bash中不支持多维数组的概念,所以

${persons[0][name]}

不起作用。但是,从Bash 4.0开始,bash具有关联数组,您似乎已尝试过它们,这些数组适合您的测试用例。例如,您可以像下面这样做:

#!/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