Associative Arrays
The associative array is a new feature in bash version 4. Associative arrays link (associate) the value and the index together, so you can associate metadata with the actual data. You can use this to associate a musician with his instrument. An associative array must be declared as such with the uppercase declare -A command.
$ cat musicians.sh #!/bin/bash declare -A beatles beatles=( [singer]=John [bassist]=Paul [drummer]=Ringo [guitarist]=George ) for musician in singer bassist drummer guitarist do echo "The ${musician} is ${beatles[$musician]}." Done $ ./musicians.sh The singer is John. The bassist is Paul. The drummer is Ringo. The guitarist is George. $
musicians.sh
Before associative arrays were introduced to bash, it was obvious that ${beatles[index]} did not make sense; it was automatically interpreted as ${beatles[$index]}. However, because an associative array can have text as the index, ${beatles["index"]} can now be valid, so the dollar sign is compulsory for associative arrays. If the dollar sign was omitted, the word “index,” and not the value of the variable $index, would be interpreted as the index of the array.
What makes associative arrays even more useful is the ability to reference back to the name of the index. This means that given ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access