Bash supports two types of arrays:
- Integer-indexed arrays
- Associative arrays
Example: Integer-indexed array
array=( "John Smith" "Mary Jones" )
echo "${array[0]}"
echo "${array[1]}"
Output:
John Smith
Mary Jones
Example: Looping thrugh integer-indexed array
array=( "John Smith" "Mary Jones" )
for u in "${array[@]}"
do
echo "Employee name: $u"
done
Output:
John Smith
Mary Jones
Example: Associative array
declare -A array
array[make]=Ford
array[model]=Mustang
array[color]=Blue
echo ${array[make]}
echo ${array[model]}
echo ${array[color]}
Output:
Ford
Mustang
Blue
Example: Looping through an associative array
The -e below allows for the use of special characters in the echo line, in this case the \t used to tab over.
declare -A array
array[Make]=Ford
array[Model]=Mustang
array[Color]=Blue
for i in "${!array[@]}"
do
make=$i
model=${array[$i]}
echo -e "$make \t $model"
done
Output:
Color Blue
Make Ford
Model Mustang