Объединение словарей

Массивы и коллекции / Словари

#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)"
}

#copies every pair of the second dictionary into the first one
mergeDict() {
    local -n to=$1 from=$2
    local key
    for key in "${!from[@]}"; do
        to[$key]=${from[$key]}
    done
}

declare -A d1=([1]="one")
declare -A d2=([2]="two")
declare -A d3=([3]="three" [1]="ONE")

declare -A dAll=()
mergeDict dAll d1
mergeDict dAll d2
#dAll is ([1]="one" [2]="two")
printDict dAll

#the same key: the value of the later dictionary wins
mergeDict dAll d3
#dAll is ([1]="ONE" [2]="two" [3]="three")
printDict dAll