默认值

数组和集合 / 字典

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

declare -A dic=([1]="A" [2]="B" [3]="")

#:- gives the default value for a missing key and for an empty value
value4=${dic[4]:-"-"}
#value4 is "-"
value3=${dic[3]:-"-"}
#value3 is "-"

#- without : gives the default value only for a missing key
value3Set=${dic[3]-"-"}
#value3Set is ""

#:= also puts the default value into the dictionary;
#: is a command that does nothing, it only lets the expansion run
: "${dic[5]:="-"}"
#dic is ([1]="A" [2]="B" [3]="" [5]="-")

echo "value4 is $value4"
echo "value3 is $value3"
echo "value3Set is \"$value3Set\""
printDict dic