如何在Bash中迭代關聯數組

基於Bash腳本中的關聯數組,我須要對其進行迭代以獲取鍵和值。 數組

#!/bin/bash

declare -A array
array[foo]=bar
array[bar]=foo

我實際上不了解在使用for-in循環時如何獲取密鑰。 bash


#1樓

您可使用${!array[@]}訪問密鑰: 函數

bash-4.0$ echo "${!array[@]}"
foo bar

而後,輕鬆遍歷鍵/值對: spa

for i in "${!array[@]}"
do
  echo "key :" $i
  echo "value:" ${array[$i]}
done

#2樓

使用感嘆號${!array[@]}訪問鍵,使用${array[@]}訪問code

您能夠像這樣遍歷鍵/值對: three

for i in "${!array[@]}"
do
  echo "key  : $i"
  echo "value: ${array[$i]}"
done

請注意在for語句中變量周圍使用引號(加上@代替* )。 若是任何鍵包含空格,則這是必需的。 element

另外一個答案的混亂來自於這樣一個事實,即您的問題包括鍵值的「 foo」和「 bar」。 get


#3樓

使用此高階函數來防止厄運金字塔 it

foreach(){ 
  arr="$(declare -p $1)" ; eval "declare -A f="${arr#*=}; 
  for i in ${!f[@]}; do $2 "$i" "${f[$i]}"; done
}

例: io

$ bar(){ echo "$1 -> $2"; }
$ declare -A foo["flap"]="three four" foo["flop"]="one two"
$ foreach foo bar
flap -> three four
flop -> one two

#4樓

declare -a arr
echo "-------------------------------------"
echo "Here another example with arr numeric"
echo "-------------------------------------"
arr=( 10 200 3000 40000 500000 60 700 8000 90000 100000 )

echo -e "\n Elements in arr are:\n ${arr[0]} \n ${arr[1]} \n ${arr[2]} \n ${arr[3]} \n ${arr[4]} \n ${arr[5]} \n ${arr[6]} \n ${arr[7]} \n ${arr[8]} \n ${arr[9]}"

echo -e " \n Total elements in arr are : ${arr[*]} \n"

echo -e " \n Total lenght of arr is : ${#arr[@]} \n"

for (( i=0; i<10; i++ ))
do      echo "The value in position $i for arr is [ ${arr[i]} ]"
done

for (( j=0; j<10; j++ ))
do      echo "The length in element $j is ${#arr[j]}"
done

for z in "${!arr[@]}"
do      echo "The key ID is $z"
done
~
相關文章
相關標籤/搜索