5. Arrays

Bash supports indexed and associative arrays. An indexed array is declared by the declare command:

$ declare -a vegetables

Or simply by the "()" operator without declare:

$ fruits=(orange lemon apple banana)

The array elements are accessed by their indexes within parameter expansion:

$ echo ${fruits[0]}
orange

and set by their indexes without parameter expansion:

$ fruits[2]=kiwi;

The first index is 0. Each value of an array element is expanded to a proper word using the subscripts "@" or "*":

$ echo ${fruits[@]}
orange lemon kiwi banana

The number of array elements can be expanded using the "#" operator:

$ echo ${#fruits[@]}
4

Within double quotes subscript "@" still expands each value to a word:

$ words=("${fruits[@]}");
$ echo ${#words[@]}
4

but "*" expands all array elements to a single word separated by the first character of the IFS parameter:

$ word=("${fruits[*]}");
$ echo ${#word[*]}
1

To expand the indexes of any array indirect, expansion by the "!" operator is used:

echo ${!fruits[@]}
0 1 2 3

To append an indexed array to another, the concatenation operator "+=" is used:

$ fruits+=(strawberry cranberry)

To unset an array element or the whole array, the unset command is used:

$ unset fruits[2]
$ echo ${fruits[@]}
orange lemon banana strawberry cranberry

An associative array has to be declared explicit by the declare command:

$ declare -A assoc

Everything described above to indexed arrays can be done to associative arrays, except the use of the "()" and "+=" operators. An approach to find the last added key-value-pair of an associative array is:

$ declare -A assoc;
$ assoc[mem]=128;
$ assoc[shared]=2;
$ assoc[swap]=64;
$ assoc[free]=4;
$ keys=(${!assoc[@]})
$ echo ${keys[$((${#keys[@]}-1))]};
free