Associative Array
noun
say it: “uh-SOH-shee-ay-tiv uh-RAY” /əˈsoʊʃiˌeɪtɪv əˈreɪ/
An array that finds each value by a name, its key, instead of a number, such as a total for each mood in a playlist.
What is an associative array in bash?
An associative array is a row of labeled envelopes: each value is found by a name, its key, instead of a slot number. Make it with declare -A first, or bash makes a numbered array. "${!total[@]}" lists the keys, in no set order. It needs bash 4 or newer.
declare -A total
while read -r mood minutes title; do
total[$mood]=$(( total[$mood] + minutes ))
done < playlist.txt
echo "${total[chill]}" # 15
echo "${total[upbeat]}" # 10
In a sentence
- “An associative array kept a total for chill, upbeat and singalong without the script knowing the moods in advance.”
- “Sam added up a month's spending per category in an associative array.”
Level: Freelancer · More Unix terms at this level
Updated