5. Arrays
Bash supports indexed and associative arrays. An indexed array is declared by the declare command:
$ declare -a vegetablesOr 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]}
orangeand 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 bananaThe number of array elements can be expanded using the "#" operator:
$ echo ${#fruits[@]}
4Within double quotes subscript "@" still expands each value to a word:
$ words=("${fruits[@]}");
$ echo ${#words[@]}
4but "*" expands all array elements to a single word separated by the first character of the IFS parameter:
$ word=("${fruits[*]}");
$ echo ${#word[*]}
1To expand the indexes of any array indirect, expansion by the "!" operator is used:
echo ${!fruits[@]}
0 1 2 3To 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 cranberryAn associative array has to be declared explicit by the declare command:
$ declare -A assocEverything 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