从bash的字典数组中获取值

从bash的字典数组中获取值,bash,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 ech

我正在学习如何编写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

Bash不支持多维数组的概念,因此

这是行不通的。然而,在Bash4.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

bash不支持二维数组。使用perl、php、python等@anubhava然后如果我想做一个curl并将输出保存到一个变量,我可以访问变量的某个值吗?其他语言将有自己的库用于在内部获取URL;您不需要执行像curl这样的外部程序,所以在这种情况下,我可以将id保存为索引?但是如果我只想搜索id,如果我只有名字怎么办?@AlbertoLópezPérez你可以反转for循环,等待我的编辑。好的,这在我的情况下是有效的,但是如果不是id,例如。。。我想,这个国家会有所不同。如果我错了,请纠正我。好吧,如果你必须有国家->名称组合,你不能用这种方法。。因为国家对个人来说不是唯一的。是的,但我真正想要的是:person[name]=Bob person[country]=西班牙persons[0]=person拥有一个结构化变量,以便以后进行foreach或其他操作,并对数据进行处理。
#!/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