Indexed Arrays in Bash

Arrays can be particularly useful when you need to work with a collection of related data items, rather than using multiple individual variables.
Indexed Arrays in Bash

On this page

In programming, arrays are a fundamental data structure that allows you to store multiple values under a single variable name. Arrays can be particularly useful when you need to work with a collection of related data items, rather than using multiple individual variables. This becomes increasingly beneficial as the number of data items grows, making it more convenient and organized to manage them as an array.

Bash, being a powerful scripting language, provides built-in support for arrays, allowing you to store and manipulate collections of data efficiently. Indexed arrays, also known as numerically indexed arrays, are a type of array where each element is associated with a numerical index, starting from zero. Bash also supports another type of array called associative arrays, which use strings as keys instead of numerical indices. In this article, we'll focus on indexed arrays, and associative arrays will be covered in a separate article.

Bash Array Declaration

In Bash, you can declare an array in two ways: using the declare keyword or by simple assignment. Additionally, Bash arrays can store elements of different data types, including strings, numbers, and even other arrays (known as multidimensional arrays).

Declaring an array using declare:

declare -a myArray

Declaring an array without declare:

myArray=()

Both methods create an empty indexed array named myArray.

Bash Array Operations

Once you have declared an array in Bash, you can perform various operations on it, such as accessing elements, adding or removing elements, updating values, retrieving the array size, and iterating over its elements. In the following sections, we'll explore different array operations in detail, along with code examples to illustrate their usage.

Accessing Array Elements

To access an individual element in an indexed array, you use the array name followed by the index enclosed in square brackets []. Remember, array indices in Bash start from zero.

myArray=(apple banana orange)
echo "${myArray[0]}"  # Output: apple
echo "${myArray[2]}"  # Output: orange

Get the Last Element of an Array

To access the last element of an array, you can use the ${myArray[@]: -1} syntax, which retrieves the last element regardless of the array's length.

myArray=(apple banana orange)
echo "${myArray[@]: -1}"  # Output: orange

Adding Elements to a Bash Array

You can add new elements to an existing array by using the compound assignment operator +=. This allows you to append elements to the end of the array.

myArray=(apple banana)
myArray+=(orange lemon)
echo "${myArray[@]}"  # Output: apple banana orange lemon

Update Array Elements

To update an existing element in an array, simply assign a new value to the desired index.

myArray=(apple banana orange)
myArray[1]=pear
echo "${myArray[@]}"  # Output: apple pear orange

Deleting an Element from the Bash Array

Bash provides the unset command to remove elements from an array. You can unset an individual element by specifying its index or unset the entire array by omitting the index.

myArray=(apple banana orange)
unset myArray[1]  # Remove the element at index 1
echo "${myArray[@]}"  # Output: apple orange

unset myArray  # Remove the entire array
echo "${myArray[@]}"  # Output: (empty)

Array Assignment Using Brace Expansion

You can also initialize arrays using brace expansion. This technique allows you to create arrays with a sequence of values or patterns, making it convenient to populate arrays with a range of elements.

ARRAY1=(foo{1..2}) # => foo1 foo2
ARRAY2=({A..D})    # => A B C D
ARRAY3=({1..5})    # => 1 2 3 4 5
ARRAY4=({A..B}{1..2}) # => A1 A2 B1 B2

Getting the Size of a Bash Array

To get the number of elements in an array, you can use the ${#myArray[@]} syntax, which returns the length of the array.

myArray=(apple banana orange)
echo "${#myArray[@]}"  # Output: 3

Loop Through Array Elements

Bash provides several ways to loop through the elements of an array. One common method is to use a for loop with the ${myArray[@]} syntax.

myArray=(apple banana orange)
for item in "${myArray[@]}"; do
    echo "Fruit: $item"
done

This will output:

Fruit: apple
Fruit: banana
Fruit: orange

Summing up

Indexed arrays in Bash provide a powerful and flexible way to manage collections of related data items. By understanding how to declare, access, modify, and iterate over array elements, you can write more efficient and organized Bash scripts. The ability to store different data types within an array further enhances its versatility, making it a valuable tool in your Bash scripting arsenal.

Subscribe to sysxplore newsletter and stay updated.

Don't miss anything. Get all the latest posts delivered straight to your inbox. It's free!
Great! Check your inbox and click the link to confirm your subscription.
Error! Please enter a valid email address!