English English French French Spanish Spanish German German
Geekflare is supported by our audience. We may earn affiliate commissions from buying links on this site.
Share on:

A Guide to Bash Arrays

A-Guide-to-Bash-Arrays
Invicti Web Application Security Scanner – the only solution that delivers automatic verification of vulnerabilities with Proof-Based Scanning™.

In this guide on Bash arrays, you’ll learn how to declare and work with indexed and associative arrays in Bash.

In Bash, you can create arrays to store a collection of elements. Bash arrays are one-dimensional collections. In programming languages such as C and C++, arrays are collections of elements of the same data type. However, in Bash, depending on the use case, you can store integers and strings in the same array.

In this tutorial, you’ll learn how to declare a Bash array and access its elements. You’ll then learn how to loop through the elements of an array and append elements to an array. Finally, you’ll learn about associative arrays in Bash. 

Let’s begin!

Interested in coding along? Here are the prerequisites:

How to Declare a Bash Array

In this section, you’ll learn the syntax to declare a Bash array and code examples.

Syntax of Bash Array Declaration

You can declare an array in Bash using the following syntax:

$ arrayName=(elt1 elt2 ... eltN)

# arrayName is the name of the array
# elt1 through eltN are the N elements in the array

In the above syntax, arrayName denotes the name of the array that contains N elements elt1...eltN.

The elements of an array are enclosed between the opening and closing parentheses (). Also, notice that the elements of the array are separated by a whitespace. As with any Bash variable, there should be no whitespace before or after the assignment operator =.

📑 In most other programming languages, you’ll separate the elements of an array or similar collections by commas. But in Bash, whitespace is the separator.

In Bash, such arrays in which the elements are identified by their index is referred to as indexed array.

Declaring Indexed Arrays in Bash

Let’s create prices, an array of numbers.

$ prices=(24 27 18 30 15)

As mentioned in the syntax, the numbers in the prices array are separated by a whitespace, enclosed in parentheses, with no spaces before and after the = assignment operator.

In Bash, you can use the echo command to print out the value of a variable. Using $variableName prints out the value of variableName. However, you can see that using the name of the array prints out only the first element.

$ echo $prices
24

Bash arrays follow zero indexing. So the first element is at index 0, the second element is at index 1, and so on. You can also use negative indexing; the index of the last array element is -1.

What happens if you try to access the element at a particular index and print it out? Let’s try printing out the element at index 1.

$ echo $prices[1]
24[1]

Why is the output 24[1]? 🤔 This is because Bash substitutes $prices with 24, the first element in the array and [1] is printed out as such.

To print out the element at a particular index, you can use the parameter expansion of the form ${prices[index]}.

$ echo ${prices[1]}
# 27
$ echo ${prices[2]}
# 18

To print out all the elements in the array, you can specify @ instead of a specific index.

$ echo ${prices[@]}
24 27 18 30 15

Next, let’s create an array of strings. Running the following command creates an indexed array:

$ declare -a fruits

The option -a creates an indexed array. You can now populate the array, one element at a time, by declaring the element at a specific index, as shown below:

$ fruits[0]="cherry"
$ fruits[1]="berry"
$ fruits[2]="apple"
$ fruits[3]="pear"
$ fruits[4]="melon"
$ fruits[5]="orange"

Now, to print out all the elements of the array, you can use ${fruits[@]}.

$ echo ${fruits[@]}
cherry berry apple pear melon orange

Access the Elements of a Bash Array

bash-array-access-elements

You can access the elements of the array in the following ways:

  • Loop through the array and access the element directly
  • Loop through the set of indexes and access elements at a specific index

Loop Through the Array and Access Elements

If you’ve coded in Python, you’ll have used the for loop using the following syntax:

for elt in some_list:
    print(elt)

Now let us write the Bash equivalent of the above for loop.

We know that {prices[@]} expands to all the elements in the prices array. And ${prices[@]} gives us the values of all the elements.

The Bash for loop is similar to Python’s for loop syntax, but the statements in the loop body should be enclosed within do and done, as shown:

$ for price in ${prices[@]}
> do
> echo $price
> done

Because we use the echo command and print out the value of the variable price, we get the following output:

# output
24
27
18
30
15

Access the Elements Using the Array Index

Another way to loop through arrays is using the index of the elements. This is similar to the for loop construct in Python is using the range() function:

for i in range(len(some_list)):
    print(i)

To get a list of indexes to loop through, you can place an exclamation point (!) before the array name in the parameter expansion. This will give you the list of all valid indexes for the array, as shown:

$ echo ${!prices[@]}
0 1 2 3 4

The prices array contains 5 elements, so the index starts at 0 and goes up to 4.

Next, we can loop through the list of indexes and access the element at each index. For index i, ${prices[i]} is the element at the index i.

$ for i in ${!prices[@]}
> do
> echo ${prices[i]}
> done

The above loop prints out all the elements in the array.

# output
24
27
18
30
15

💬 Here, after accessing each element, we perform a simple operation of printing out its value. In general, we can have any valid processing on the elements.

Append Elements to a Bash Array

Guide-to-Bash-Arrays

In the prices array, we have five elements (at indexes 0,1,2,3 and 4). If you want to add an element to the end of the array at index 5, you can do so as follows:

$ prices[5]=21

We see that 21 has been appended to the end of the prices array.

$ echo ${prices[@]}
24 27 18 30 15 21

However, it is more convenient to append to the end of the array—without remembering—the index of the last added element or the number of elements currently in the array.

You can use arrayName+=(elements(s)) it to append one or more elements to an array, as shown:

$ prices+=(10)

Now, if we print out the prices array, we see that 10 has been appended to the end of the array.

$ echo ${prices[@]}
24 27 18 30 15 21 10

Next, let’s learn how to declare associative arrays in Bash.

Associative Arrays in Bash

If you want to define a relationship in terms of key-value pairs, you can use an associative array. You can declare an associative array using the following general syntax. Notice that we use the -A option instead of -a.

$ declare -A fruits_prices

You can add elements to the associative array by specifying the key and the corresponding value. Here, we have added the names of the fruits as the keys and the numbers from the prices array as the values.

$ fruits_prices[cherry]=24
$ fruits_prices[berry]=27
$ fruits_prices[apple]=18
$ fruits_prices[pear]=30
$ fruits_prices[melon]=15
$ fruits_prices[orange]=21

So how do we access the elements in an associative array?

Just the way you’d look up the value using the corresponding key in a Python dictionary, you can access the values in an associative array using the keys.

$ echo ${fruits_prices[berry]}
# 27

We see that ${fruits_prices[@]} expands to the values and ${!fruits_prices[@]} expands to the keys.

$ echo ${fruits_prices[@]}
# Output: 18 27 21 24 30 15
$ echo ${!fruits_prices[@]}
# Output: apple berry orange cherry pear melon

Note: The order of elements is not the same as the order in which we added them. This is because, unlike indexed arrays, associative arrays are not ordered collections. Rather, they work on the association between the keys and the values. Therefore, keys are to associative arrays what indexes are to indexed arrays.

You can also loop through the associative array and access the keys, as shown:

$ for key in ${!fruits_prices[@]}
> do
> echo $key
> done
# Output
apple
berry
orange
cherry
pear
melon

The following loop shows how you can access the values.

$ for value in ${fruits_prices[@]}
> do
> echo $value
> done
# Output
18
27
21
24
30
15

Though it is recommended to use arrayName[key]=value,  you can also declare it as a sequence like this:

declare -A arrayName
arrayName=(key1 value1 key2 value2 ... keyN valueN)

This way, Bash infers the first element as the first key, the second element as the first value, and so on.

Summing Up

I hope you now understand how to create and work with Bash arrays. Here’s a quick review of what you have learned.

  • You can declare an indexed array in Bash using the syntax arrayName=(elt1 elt2 elt3 ... eltN) or run declare -a arrayName and add elements to the array.
  • To access the elements, you can loop through using ${arrayName[@]}. Alternatively, you can get the list of all valid indexes using the parameter expansion ${!arrayName[@]}.
  • Finally, you also learned how to declare an associative array to store key-value pairs in Bash.

Next, check out the tutorial for loops in Bash.

Thanks to our Sponsors
More great readings on Development
Power Your Business
Some of the tools and services to help your business grow.
  • Invicti uses the Proof-Based Scanning™ to automatically verify the identified vulnerabilities and generate actionable results within just hours.
    Try Invicti
  • Web scraping, residential proxy, proxy manager, web unlocker, search engine crawler, and all you need to collect web data.
    Try Brightdata
  • Semrush is an all-in-one digital marketing solution with more than 50 tools in SEO, social media, and content marketing.
    Try Semrush
  • Intruder is an online vulnerability scanner that finds cyber security weaknesses in your infrastructure, to avoid costly data breaches.
    Try Intruder