Introduction
Arrays let you store many values in one place. Accessing array elements means getting the value you want from that list.
array_name=(value1 value2 value3 ...)
# Access element at index i (starting from 0):
element=${array_name[i]}fruits=(apple banana cherry)
echo ${fruits[0]}numbers=(10 20 30 40) echo ${numbers[3]}
empty=()
echo ${empty[0]}single=(onlyone)
echo ${single[0]}#!/bin/bash # Create an array of colors colors=(red green blue yellow) # Print the whole array echo "All colors: ${colors[*]}" # Access and print the first color first_color=${colors[0]} echo "First color: $first_color" # Access and print the last color last_index=$((${#colors[@]} - 1)) last_color=${colors[$last_index]} echo "Last color: $last_color" # Try to access an index that does not exist missing_color=${colors[10]} echo "Missing color at index 10: '$missing_color'"
fruits?${array_name[index]}. So, ${fruits[0]} gets the first element.colors in Bash?${array_name[index]}. So, ${colors[2]} is correct.numbers=(10 20 30 40), what is the output of echo ${numbers[3]}?numbers has elements: index 0=10, 1=20, 2=30, 3=40.${numbers[3]} returns the element at index 3, which is 40.my_array=(apple banana cherry)
echo ${my_array[3]}items=(pen notebook eraser). You want to print the last element without hardcoding the index. Which command achieves this?${#items[@]} gives the number of elements (3). Last index is length minus 1 (2).${items[${#items[@]}-1]} to get last element dynamically.Pass the test and this pattern moves unknown