2017-06-22 102 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,例如......國家,我認爲這會有所不同。如果我錯了,請糾正我。 –