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 guide.
📚BONUS
Stay tuned until the end of this article for something special: a full copy of my Bash Scripting Handbook, normally $25.
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.
Keep reading with a 7-day free trial
Subscribe to sysxplore to keep reading this post and get 7 days of free access to the full post archives.