Example-1: Numeric Array Declaration:
The default index of any array is numeric and all values are taken as string value. A simple numeric array of 5 string values are declared here. echo command is used here to print each array values separately. If you want to print all values of array by single echo command then “*” symbol has to use in the index of the array. These two options are shown in the following example.
MyArray=( HTML Javascript CSS JQuery Bootstrap )
# Print 5 values individually
echo "———-Print 5 values individually—————"
echo ${MyArray[0]}
echo ${MyArray[1]}
echo ${MyArray[2]}
echo ${MyArray[3]}
echo ${MyArray[4]}
#Print all values by using *
echo "—————–Print all values——————-"
echo ${MyArray[*]}
Output:
Example-2: Associative Array Declaration:
Each index of the array needs to be declared separately in associative array. An associative array of 4 elements is declared in the following examples. You can read the values of the each index separately like previous example by defining the index value. You can print only indexes of associative array by using “!” and “@” symbol.
# Associative array declaration
declare -A MyArr
# Value Initialization
MyArr=( [mark]=79 [john]=93 [ella]=87 [mila]=83 )
# Print values
echo ${MyArr[mark]}
echo ${MyArr[john]}
echo ${MyArr[ella]}
echo ${MyArr[mila]}
#Print indexes
echo ${!MyArr[@]}
Output:
Example-3: Reading Array values using for loop:
You can easily count the total number of elements of any bash array by using “#” and “*” symbol which is shown in the first part of the following example. For loop is commonly used to iterate the values of any array. You can also read array values and array indexes separately by using for loops. Different for loops are used in the following example to read array indexes, array values and both.
# Associative array declaration
declare -A MyArr
# Value Initialization
MyArr=( [os]=Windows [web]=PHP [db]=Oracle )
echo "Total number of elements=${#MyArr[*]}"
echo "Array values are"
for value in ${MyArr[@]}
do
echo $value
done
echo "Array indexes are"
for key in ${!MyArr[@]}
do
echo $key
done
echo "Array values and indexes:"
for key in ${!MyArr[*]}
do
echo "$key => ${MyArr[$key]}"
done
Output:
Video of this lesson here:
There are many uses of array in programming. Some common and very simple uses of array in bash are shown in this tutorial. After exercising the above examples your basic concept of bash array will be cleared and you will be able to use bash array appropriately in your script.