Introduction
Arrays let you keep many pieces of related information together in one place. This helps you organize and work with lists of data easily.
declare -a array_name array_name=(item1 item2 item3 ...) # Access item: ${array_name[index]} # Get all items: ${array_name[@]}
declare -a fruits
fruits=(apple banana cherry)
echo ${fruits[0]}declare -a empty_array
# This array has no items yet
echo ${empty_array[@]}declare -a single_item
single_item=(onlyone)
echo ${single_item[0]}declare -a colors
colors=(red green blue)
echo ${colors[2]}#!/bin/bash # Create an array of animals declare -a animals animals=(dog cat bird) # Print all animals before adding echo "Animals before adding: ${animals[@]}" # Add a new animal animals+=(fish) # Print all animals after adding echo "Animals after adding: ${animals[@]}" # Print the first animal echo "First animal: ${animals[0]}" # Print the last animal last_index=$((${#animals[@]} - 1)) echo "Last animal: ${animals[$last_index]}"
fruits with items apple, banana, and cherry in bash?colors=(red green blue)
echo ${colors[1]}myarray=(one two three) echo $myarray[2]
Pass the test and this pattern moves unknown