Arrays allow a script to store a collection of data as separate entities using indices. Bash supports both regular arrays that use integers as the array index, and associative arrays, which use a string as the array index. Regular arrays should be used when the data is organized numerically, for example, a set of successive iterations. Associative arrays can be used when the data is organized by a string, for example, host names. In this recipe, we will see how to use both of these.
Arrays and associative arrays
Getting ready
To use associate arrays, you must have Bash Version 4 or higher.
How to do it...
Arrays can be defined using different techniques:
- Define an array using a list of values in a single line:
array_var=(test1 test2 test3 test4) #Values will be stored in consecutive locations starting from index 0.
Alternately, define an array as a set of index-value pairs:
array_var[0]="test1" array_var[1]="test2" array_var[2]="test3" array_var[3]="test4" array_var[4]="test5" array_var[5]="test6"
- Print the contents of an array at a given index using the following commands:
echo ${array_var[0]} test1 index=5 echo ${array_var[$index]} test6
- Print all of the values in an array as a list, using the following commands:
$ echo ${array_var[*]} test1 test2 test3 test4 test5 test6
Alternately, you can use the following command:
$ echo ${array_var[@]} test1 test2 test3 test4 test5 test6
- Print the length of an array (the number of elements in an array):
$ echo ${#array_var[*]}6
There's more...
Associative arrays have been introduced to Bash from Version 4.0. When the indices are a string (site names, user names, nonsequential numbers, and so on), an associative array is easier to work with than a numerically indexed array.
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
Listing of array indexes
Arrays have indexes for indexing each of the elements. Ordinary and associative arrays differ in terms of index type.
Obtain the list of indexes in an array.
$ echo ${!array_var[*]}
Alternatively, we can also use the following command:
$ echo ${!array_var[@]}
In the previous fruits_value array example, consider the following command:
$ echo ${!fruits_value[*]} orange apple
This will work for ordinary arrays too.