Defining associative arrays

An associative array can use any text data as an array index. A declaration statement is required to define a variable name as an associative array:

$ declare -A ass_array

After the declaration, elements are added to the associative array using either of these two methods:

  • Inline index-value list method:
        $ ass_array=([index1]=val1 [index2]=val2)
  • Separate index-value assignments:
        $ ass_array[index1]=val1
        $ ass_array'index2]=val2

For example, consider the assignment of prices for fruits, using an associative array:

$ declare -A fruits_value
$ fruits_value=([apple]='100 dollars' [orange]='150 dollars')

Display the contents of an array:

$ echo "Apple costs ${fruits_value[apple]}"
Apple costs 100 dollars ...

Get Linux Shell Scripting Cookbook - Third Edition 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.