#prints the pairs of an associative array sorted by key,
#in the form of declare -p, which keeps no stable order
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)"
}
#an associative array is the bash dictionary (bash 4.0 and newer)
declare -A d1=()
#d1 is ()
declare -A d2=([1]="one" [2]="two")
#d2 is ([1]="one" [2]="two")
#bash 5.1 and newer: the pairs as a list "key value key value"
declare -A d3=(one 1 two 2)
#d3 is ([one]="1" [two]="2")
#bash cannot copy a dictionary in one step: copy the pairs in a loop
declare -A d4=()
for key in "${!d3[@]}"; do
d4[$key]=${d3[$key]}
done
d4[three]=3
#d4 is ([one]="1" [three]="3" [two]="2")
#without declare -A the array is indexed: the key "one" is read
#as a variable in arithmetic, it is 0, so both values go to index 0
notDict=([one]=1 [two]=2)
#notDict is (2)
printDict d1
printDict d2
printDict d3
printDict d4
echo "notDict is (${notDict[*]})"