Working with Arrays in Bash
Scripting·3 min read·Feb 24, 2025
As a reminder, an array is a type of variable that contains a collection of data organized into a list or sequence.
Arrays are declared using parenthesis () and each element within it is separated by a space character.
array=(element1 ... elementN)Accessing array elements
When declaring an array, each of its elements (or values) is automatically associated with a unique numerical position called an index, where the first element is stored at index 0, the second at index 1, and so on.
To access and use the value stored at a specific index, you can use this syntax:
${array[index]}Where:
-
arrayis the name of the variable containing the array. -
indexis the index you want to access the value of.
On the other hand, to access all the values of an array at once, separated by a single space character, you can use the special @ index:
Unlock the CLI & Scripting with Bash module
Learn how to gain advanced control over the OS and automate complex routine tasks prone to manual errors with the CLI and Bash scripting.
You get immediate access to:
- 34 focused lessons across the CLI and Bash
- 4 real-world projects with commented solutions
- Ongoing updates to this bundle
- Lifetime access to this bundle