The Ops Community

Tarush Arora
Tarush Arora

Posted on

Introduction to Bash Arrays

Cover Image

Bash scripts play an essential role in deploying cloud infrastructures, as most high-performing machines run on the Linux operating system.

And bash arrays are always an essential part of every significant bash script.

This article will teach the basics of bash arrays, starting from declaring them in Linux to passing them in a function.
So, let’s get started and understand bash array.

Bash Array is a one-dimensional data structure that helps store different values in an organized manner. Indexed and Associative are two of its types, which hold the integer and string values in reference to indices, known as index position or a key.

You must have seen arrays in many programming languages, but bash arrays are pretty different.

It allows the addition of different types of data types in a single array and can manage contrasting variables and provide accurate output.

Bash Array vs String

In bash, you will find both arrays and strings.

However, both are enormously different from each other.

Where, array is a primary bash data structure, string is a data type, which you can store in an array.

For Example: A string can be hello, windows, Linux, etc. Contrastingly, array is a data structure, which can hold a number of strings in it.
You can declare an array and add strings into it, such as:
declare -a my_array #command to create an array
my_array=(hello windows Linux) #command to store strings in an array

Therefore, arrays are used to store strings.

Bash Array vs List

Likewise, other programming languages, there are no lists in bash scripting.
It only offers indexed and associative arrays for storing the variables and displaying them as list.
Array uses index values for referencing the elements, leveraging to display stored variables in a list view.
For Example:
declare -a my_array #creating array
my_array=(one two three) #inserting elements into array
echo ${my_array[@]) #displaying elements in a list view as per the array index
Output:
one
two
three

Discussion (0)