0
0
Bash Scriptingscripting~5 mins

Indexed array declaration in Bash Scripting

Choose your learning style9 modes available
Introduction
Arrays let you store many values in one place. Indexed arrays use numbers to find each value easily.
You want to keep a list of file names to process one by one.
You need to store multiple user inputs and use them later.
You want to save a list of commands to run in order.
You want to group related data like days of the week or colors.
Syntax
Bash Scripting
array_name=(value1 value2 value3 ...)
# or
declare -a array_name
array_name=(value1 value2 value3 ...)
Use parentheses () to list values separated by spaces.
Array indexes start at 0 by default.
Examples
Creates an array named fruits with three items. Prints the first item: apple.
Bash Scripting
fruits=(apple banana cherry)
echo ${fruits[0]}
Declares an indexed array colors, assigns three colors, and prints the third item: blue.
Bash Scripting
declare -a colors
colors=(red green blue)
echo ${colors[2]}
Creates an empty array and prints its length: 0.
Bash Scripting
empty_array=()
echo ${#empty_array[@]}
Array with one number. Prints 10.
Bash Scripting
numbers=(10)
echo ${numbers[0]}
Sample Program
This script shows how to declare an indexed array, access items by index, add a new item, and get the array length.
Bash Scripting
#!/bin/bash

# Declare an indexed array of fruits
fruits=(apple banana cherry)

# Print all fruits
echo "All fruits: ${fruits[@]}"

# Print the first fruit
echo "First fruit: ${fruits[0]}"

# Add a new fruit
fruits+=(date)

# Print all fruits after adding
echo "Fruits after adding one: ${fruits[@]}"

# Print number of fruits
echo "Number of fruits: ${#fruits[@]}"
OutputSuccess
Important Notes
Access array elements using ${array_name[index]} where index starts at 0.
Use ${#array_name[@]} to get the number of elements in the array.
Adding elements can be done with array+=(new_value).
Arrays in bash are zero-based and can hold strings or numbers.
Common mistake: forgetting parentheses when declaring arrays causes errors.
Use indexed arrays when order matters and you want to access by position.
Summary
Indexed arrays store multiple values accessed by number starting at zero.
Declare arrays with parentheses and separate values by spaces.
Use ${array[index]} to get an item and ${#array[@]} to get the count.