2017-06-22 104 views
0

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

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

谢谢您的阅读!

猛砸版本:48年3月4日

+1

bash不支持2维数组。使用'perl','php','python'等 – anubhava

+0

@anubhava然后,如果我想要例如做一个卷曲并保存输出到一个变量我可以访问一些变量的值? –

+0

其他语言将拥有自己的库,用于在内部获取URL;你不需要执行像curl这样的外部程序。 – chepner

回答

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 
+0

那么在这种情况下,我可以将ID保存为索引?但如果我想搜索该ID,如果我只有名字,该怎么办? –

+0

@AlbertoLópezPérez你可以逆转for循环,等待我的编辑。 – sjsam

+0

好的,这在我的情况下是有效的,但是如果不是IDS,例如......国家,我认为这会有所不同。如果我错了,请纠正我。 –