When you want to store multiple values in a single variable then the most appropriate data structure is array. There are two types of array in Bash-
arrayvariable=(element1 element2 element3 ... elementn)
Here, each value in an array is separated by a space.
homo=(12 24 36 48) hete=("Oreo" 8)
Array in bash follows zero-based indexing which means the index position starts from zero. The first element in the array is assigned an index of zero. In order to access the elements of an array, enclose index position in square brackets. Follow the below syntax to understand it properly-
${arrayname[indexposition]}
os=("Android" "iOS" "Window") echo "First element of array: ${os[0]}" echo "Second element of array: ${os[1]}" echo "Third element of array: ${os[2]}"
Output of the above program
First element of array: Android Second element of array: iOS Third element of array: Window
android=("Kitkat" "Lollipop" "Marshmallow") echo "Array element before modification" echo "First element of array: ${android[0]}" echo "Second element of array: ${android[1]}" echo "Third element of array: ${android[2]}" echo "Array element after modification" android[0]="Oreo" android[1]="Nought" android[2]="Pie" echo "First element of array: ${android[0]}" echo "Second element of array: ${android[1]}" echo "Third element of array: ${android[2]}"
Output of the above program
Array element before modification First element of array: Kitkat Second element of array: Lollipop Third element of array: Marshmallow Array element after modification First element of array: Oreo Second element of array: Nought Third element of array: Pie
To get the number of elements in an array, use ${#arrayname[*]}
statement. If you want to know the length of each array element, use ${#arrayname[indexvalue]}
statement.
android=("Kitkat" "Lollipop" "Marshmallow") echo "Total number of elements in array: ${#android[*]}" echo "Length of first element: ${#android[0]}" echo "Length of second element: ${#android[1]}" echo "Length of third element: ${#android[2]}"
To loop through an array, follow the below syntax-
for element in ${arrayname[*]} do echo $element done
android=("Kitkat" "Lollipop" "Marshmallow") for element in ${android[*]} do echo $element done
Output of the above program
Kitkat Lollipop Marshmallow