0
0
Bash Scriptingscripting~5 mins

Accessing array elements in Bash Scripting

Choose your learning style9 modes available
Introduction
Arrays let you store many values in one place. Accessing array elements means getting the value you want from that list.
You have a list of filenames and want to open one by its position.
You store user names in an array and want to greet a specific user.
You keep a list of numbers and want to calculate something with one of them.
You want to loop through a list but also access elements by their index.
You want to update or check a specific item in a list stored in an array.
Syntax
Bash Scripting
array_name=(value1 value2 value3 ...)
# Access element at index i (starting from 0):
element=${array_name[i]}
Array indexes start at 0, so the first element is at index 0.
Use curly braces ${} to access array elements in bash.
Examples
Prints the first fruit: apple
Bash Scripting
fruits=(apple banana cherry)
echo ${fruits[0]}
Prints the fourth number: 40
Bash Scripting
numbers=(10 20 30 40)
echo ${numbers[3]}
Accessing an element in an empty array prints nothing
Bash Scripting
empty=()
echo ${empty[0]}
Accessing the only element in a single-item array
Bash Scripting
single=(onlyone)
echo ${single[0]}
Sample Program
This script shows how to create an array, access the first and last elements, and what happens when you access an index that is not set.
Bash Scripting
#!/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'"
OutputSuccess
Important Notes
Accessing an index outside the array returns an empty string, not an error.
Array length can be found with ${#array_name[@]} to help access the last element.
Remember array indexes start at 0, so last element index is length minus one.
Use arrays when you need to group related values and access them by position.
Summary
Arrays store multiple values in one variable.
Access elements using ${array_name[index]} with index starting at 0.
Out-of-range indexes return empty strings, not errors.