How to use Bash array in scripting: A complete guide

How to use Bash array in scripting: A complete guide

A Bash array is a structure in the Bash programming language that lets you group and index items, which can be strings or numbers. It helps you work with a lot of data more efficiently, streamlining various UNIX system administration tasks like storing command outputs.

You can write Bash arrays in two ways: indexed and associative. While indexed arrays assign a number to an element, the associative counterpart uses strings and requires the explicit declare shell builtin. Apart from that, you can write them using the same syntax. 

When using arrays in Bash scripts, you will often modify or channel them through different operations, such as:

  • Adding a new variable to an existing Bash array
  • Referencing and printing a specific array element
  • Removing an element from a Bash array
  • Looping through items in a Bash array
  • Passing a Bash array into a function.

Let’s dive deeper into using Bash arrays in scripting, their operations, and practical use case examples.

What is a Bash array?

A Bash array is a data structure designed to store information in an indexed way. In other words, a Bash array is a large group of variables. Unlike typical arrays used in other programming languages, arrays can store different types of elements. For example, you can use a bash array to store both strings and numbers.

Note that bash does not support multidimensional arrays, so it’s not possible to add an array within an array.

There are two types of bash arrays: indexed and associative. An indexed array is referred to by integers or numbers, which helps organize basic data. Meanwhile, an associative array is referred to via strings or a set of characters and words, suitable for storing key-value pairs.

Apart from the reference, the method of writing indexed and associative arrays also slightly differs.

How do you declare a Bash array?

Declaring a Bash array essentially means creating the index and assigning elements to it. You can also explicitly declare an array by adding the shell builtin declare with the -a flag at the beginning of your Bash script, though it’s optional in some scenarios.

For example, declaring an indexed array doesn’t need the shell builtin, but it’s mandatory if you want to declare an associative array. Apart from this rule, you can declare either arrays using the same syntax, which we’ll explain next.

Syntax overview

The basic syntax of a Bash array looks like the following:

#optional for indexed
declare -a IndexedArray
Array[subscript1]=element1
Array[subscript2]=element2
Array[subscript2]=element3

Subscript is the reference to your array elements, which are numbers for indexed arrays and strings for the associative ones. Here’s an example of an actual indexed Bash array:

#optional for indexed
declare -a IndexedArray
IndexedArray[0]=car
IndexedArray[1]=plane
IndexedArray[2]=bike

Meanwhile, an associative Bash array looks like this:

declare -a IndexedArray
AssociativeArray[color]=blue
AssociativeArray[type]=car
AssociativeArray[topspeed]=200

You can also simplify arrays by writing them in a single line using indices, like in these examples:

IndexedArray=([0]='car' [1]='plane' [2]='bike')
declare -A Associative Array=( [color]=blue [type]=car [topspeed]=200 )

Note that the first example encloses the array elements in quotation marks. This is optional, but becomes necessary when the items are space-separated strings or an empty string.

For indexed arrays specifically, you can omit the subscript when writing it in a single line because Bash automatically assigns the number at a fixed increment:

IndexedArray=(car plane bike)

Remember that indexing starts at 0, so the above example will assign the car element of the array to the 0 index.

Another interesting feature of bash arrays is that following index numbers in order is not necessary. For example, you can declare only the first and third elements while leaving the second element of an array empty:

IndexedArray[0]=car
IndexedArray[2]=bike

Now that we know how to declare an array, let’s learn about different operations for Bash array manipulation.

How do you add a variable to a Bash array?

Adding Bash variables means inserting a new element to your array using the += operator. The syntax looks like this:

ArrayName+=(element-to-add)

For example, here’s how to add a new item to an indexed array:

IndexedArray=(car plane bike)
IndexedArray+=(motorcycle)

The indexed array has a new element now. Remember that this method appends to the end of an array. Therefore, the motorcycle element will be added as the last element.

For associative arrays, the process is very similar, except you need to specify the keys along with all the elements:

declare -A AssociativeArray
AssociativeArray[color]=blue
AssociativeArray+=([tires]=alloy [engine]=gasoline)

Adding a variable is an essential operation for expanding your Bash array with new data. It is commonly used for tasks like storing command outputs and logging events on your system.

Using Bash operator for another task

In addition to appending an array with a new item, the += operator lets you concatenate strings in your Bash script.

How do you reference and print a Bash array element?

Referring to and printing a Bash array element lets you check an element associated with a specific index or key. To do this, create an indexed array:

IndexedArray=(car plane bike)

To reference the first array variable, use the following syntax:

${IndexedArray[0]}

Combine it with echo, and you will get the following:

echo ${IndexedArray[0]}

The output will show you the first element. In this case, it’s car. The same logic applies when referencing and printing an associative array:

declare -A AssociativeArray=( [color]=blue [type]=car [topspeed]=200 )
echo ${AssociativeArray[type]}

The output will be car as well.

To print the whole array, use @ as an index. The full script looks like this:

You can also print the keys of an array instead. To do this, add an exclamation mark before the array name:

Printing an element of an array is helpful for checking your script before passing it through other commands or functions, ensuring you work with the correct data.

How do you remove Bash array elements?

Deleting array elements removes a specific item from your array, using a process similar to referencing them. Use an index or a key combined with the unset builtin to delete an array element, as shown in this syntax:

unset ArrayName[index-or-key]

Here’s an example of deleting a single element from an indexed array:

A similar logic applies to associative arrays:

To delete an entire array, specify unset with the array name as shown here:

Nothing is shown after trying to print the array elements because the unset builtin deleted them. Also, this will completely remove the index from your array. For example, if you unset 1 from the following array, only 0 and 2 remain:

IndexedArray=([0]='car' [1]='plane' [2]='bike')

If you unset an index or key that doesn’t exist, your array won’t change. You also won’t get an error and the operation will complete silently.

Removing an item from your Bash arrays is common if you store dynamic data like logs. As your script expands, you may want to delete unused elements to make it more organized.

How do you loop through a Bash array?

Creating Bash loops is a fundamental aspect of learning Bash scripting basics. You can use loops with arrays as well, using this syntax:

for i in "${Array[@]}"; do action; done

For example, the most common use case is to iterate over each array item:

You can also combine keys with the array elements and print them all together like this:

Looping through an array is helpful for automating tasks involving a lot of data. For example, you can batch rename files by passing them through the mv command, or install multiple packages simultaneously using your system’s package manager.

How do you pass a Bash array to a function?

Passing a Bash array to functions saves a considerable amount of time when scripting. Instead of writing the same code repeatedly, you can call out an already-written function. We will combine the previously mentioned iteration loop and make a function out of it:

function Iteration
{
m=${#IndexedArray[@]}
for (( i=0; i<m; i++ ))
do
echo ${IndexedArray[$i]}
done
}
IndexedArray=(car bike plane)
Iteration ${IndexedArray[@]}

Running it on the command line will get you the following result:

Incorporating functions when using Bash arrays in scripting helps you complete complex tasks involving a large dataset, like parsing outputs or filtering through logs. This operation typically works together with a loop to iterate through the data.

Key takeaways

Bash array enables you to work with a large amount of data more efficiently, which is helpful when managing a UNIX-like system like a Linux VPS. In real-world applications, Bash arrays are commonly used to pass values into commands, functions, or loops. 

Since the use of Bash arrays with functions, loops, and commands varies depending on the task, we highly recommend exploring them in more detail. If you need references, check out our Bash script examples tutorial to learn more about how these scripts might look in real-world applications.

To deepen your understanding of Bash arrays’ applications, try creating a script that indexes and loops through files to perform an automated task like renaming. You can do this on your own Linux computer or set up a learning environment on Hostinger’s VPS solution

All of the tutorial content on this website is subject to Hostinger's rigorous editorial standards and values.

Author
The author

Ignas R.

Ignas takes great satisfaction in helping people tackle even the most complex technical issues. His current goal is to write easy-to-follow articles so that these issues will not happen at all. During his free time, Ignas likes to play video games and fix up things around his house.