#按键排序打印关联数组的键值对,
#形式同 declare -p,但 declare -p 的顺序并不稳定
printDict() {
local -n pairs=$1
local key line=""
for key in $(printf '%s\n' "${!pairs[@]}" | sort); do
line+="${line:+ }[$key]=\"${pairs[$key]}\""
done
echo "$1 is ($line)"
}
#关联数组就是 bash 的字典(bash 4.0 及更高版本)
declare -A d1=()
#d1 is ()
declare -A d2=([1]="one" [2]="two")
#d2 is ([1]="one" [2]="two")
#bash 5.1 及更高版本:键值对以 "key value key value" 的列表形式给出
declare -A d3=(one 1 two 2)
#d3 is ([one]="1" [two]="2")
#bash 不能一步复制字典:要在循环中逐对复制
declare -A d4=()
for key in "${!d3[@]}"; do
d4[$key]=${d3[$key]}
done
d4[three]=3
#d4 is ([one]="1" [three]="3" [two]="2")
#不加 declare -A 时是索引数组:键 "one" 在算术中被当作变量读取,
#其值为 0,所以两个值都存入索引 0
notDict=([one]=1 [two]=2)
#notDict is (2)
printDict d1
printDict d2
printDict d3
printDict d4
echo "notDict is (${notDict[*]})"