Set initialization

Arrays and collections / Sets

#prints the keys of an associative array, sorted
printSet() {
    local -n items=$1
    echo "$1 is ($(printf '%s\n' "${!items[@]}" | sort | paste -sd ' '))"
}

#bash has no set: the keys of an associative array are unique,
#so they make a set; the values do not matter
declare -A empty=()
#empty is ()

declare -A intSet=([1]=1 [2]=1 [3]=1)
#intSet is (1 2 3)

#a repeat sets the same key again
declare -A strSet=()
for word in "one" "two" "three" "two"; do
    strSet[$word]=1
done
#strSet is ("one" "three" "two")

#without declare -A the array is indexed: the key "one" is read
#as a variable in arithmetic, it is 0, so both words go to index 0
notSet=()
notSet[one]=1
notSet[two]=1
notSetCount=${#notSet[@]}
#notSetCount is 1

printSet empty
printSet intSet
printSet strSet
echo "notSetCount is $notSetCount"