Associative arrays

Bash 4.0 also introduced associative arrays, allowing string indices for arrays rather than numeric offsets, rather like a dictionary in Python, or a hash in Perl:

bash$ declare -A myassocarray
bash$ myassocarray=([apple]="red" [banana]="yellow" [carrot]="orange")
bash$ printf '%s\n' "${myassocarray[banana]}"
yellow

Be careful to declare the array with -A first if you want to use this, otherwise Bash may treat the array and operations done with it using numeric indices.

We won't use associative arrays in the rest of this book  while useful for those who want a dictionary type for shell scripting, they're a relatively new addition to the language, well outside the specifications for shell scripting languages. A case could ...

Get Bash Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.