Declare Array in Bash [Create, Initialize]

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

Bash, a widely popular and powerful shell in the world of Linux, offers diversified ways to ensure efficient data management and arrays are tools as such. However, before diving into the scripting universe, one must have complete knowledge of how to declare an array in Bash and create and initialize it. Henceforth, in this article, I have undertaken a plan to enlighten you on these quintessential concepts for data storage and manipulation in Bash scripting.

How to Declare, Create, and Initialize Arrays in Bash?

You can declare, create, or initialize Bash arrays by exploiting some simple syntax. See the syntax given below:

  1. To declare a bash array use the declare command:
    declare -a array1
  2. To create a bash array use parentheses:
    array2=()
  3. To initialize a bash array insert elements inside the parentheses:
    my_array3=(value)

What is Array Declaration, Creation, and Initialization in Bash?

The terms “array declaration,” “array creation”, and “array initialization”, each have a distinctive definition in the context of programming languages. First, let’s explore their definition:

  1. Declaration of an Array: The declaration specifies the array variable with a name and sometimes, type and it does not necessarily allocate space in memory.
  2. Creation of an Array: To create an array, means to allocate memory for the and prepare it to hold values of specified types and may not involve the initialization of values at the beginning.
  3. Initialization of an Array: The initialization of an array is to provide the array with elements to store just after it is constructed.

However, considering the differences, it is crucial to acknowledge that, in the context of Bash arrays, they are essentially the same thing and you can use the terms interchangeably in working with the arrays. To grasp a clearer gist, follow the article till the end.

Array Declaration in Bash

The declaration can be termed the foremost step when you intend to work with arrays in Bash though it is not mandatory since Bash is a dynamically typed scripting language. Still, you can practice the standard process of declaration that alerts the system of your intention to work with a variable which is an array type. Therefore, in this feature, I will cover the necessary particulars related to declaring a Bash array (both the indexed and associative arrays).

A. Declare an Indexed Array in Bash

An indexed array form references the data elements using indices starting from ‘0’. So, if an array contains two elements, the first value is placed at index 0 while the second element (last element) is at index 1. Declaring an indexed array in Bash involves a few super simple steps. Thus, the agenda of this section will primarily be to introduce you to the ways you can declare an indexed array. Specifically, I will cover the explicit, indirect, and compound assignment methods.

Method 01: Declare an Indexed Array in Bash with Explicit Method

In this method, you first declare the array that you want to work with by mentioning its type in an explicit manner. However, in Bash, there is no need for this direct declaration since it specifies the array as indexed by default. Nevertheless, you can still use the declare command and following scripting syntax like the following:

declare -a <array_name>
EXPLANATION
  • declare: Bash command used to explicitly set the array variable attribute.
  • -a: Option indicating the declaration of an indexed array.
  • <array_name>: The name you want to assign to the array.

It’s really that simple. Now, follow a bit further for demonstration where I will declare an empty array named tools. For that see the below Bash script:

#!/bin/bash

#empty array declaration
declare -a tools
echo "an empty array is declared"
EXPLANATION

In the first line of the script, #!/bin/bash, #! is called shebang. It indicates the system uses the bash interpreter for executing the script. Then, in the 3rd line,  I used the declare command with the -a option to declare the array named tools in an explicit manner. Finally, I used the echo command to print a message denoting the declaration of the tools array with no issue.

indexed array declare in Bash with create initialize.In the image, you see that I have printed a message that represents the array declaration from the script.

Note: You can also declare an empty array like the following:

arr1=()

Method 02: Declare an Indexed Array in Bash with an Indirect Method

The above scope showed how you can explicitly declare an indexed array in Bash. However, you can also handle the Bash array declaration in an implicit manner. Just assign values to the respective indices using the following line of code and Bash will automatically declare the array. The syntactic details are mentioned below:

array_name[position]=value
EXPLANATION
  • array_name: The name of the array you assign.
  • position: The index at which you want to assign value.
  • value: The item you insert to the specified index.

Following this, I will display the practical aspects using the below script where I will create an array called first_name utilizing the aforementioned syntax:

#! /bin/bash

#array declaration using indirect method
first_name[0]=shanto
first_name[1]=virat
first_name[2]=williamson

# print message if no error occurs
echo "array first_name followed indirect declaration."
EXPLANATION

In the script, I directly assigned elements to the  first_name array without declaring it. In consequence, this declares the array in the system which is evident in the last line of the code where I used the echo command and printed that I have declared the array first_name with no explicit mention.

indirect indexed array declaration in Bash and create initialize.In the above snap, I have run the script that declares an array with the indirect method.

Method 03: Declare an Indexed Array in Bash Using Compound Assignment

The compound assignment technique is generally to modify the existing state of an array by the use of compound operators (addition, subtraction, etc., followed by the assignment operator =). Nonetheless, in this case, you can use the =+ operator to add elements to an array and end up, eventually, declaring it. Now, if the array does not exist, Bash declares it. The command is:

array_name+=(item1 item2… itemN)
EXPLANATION
  • array_name: The name of the array you assign.
  • +=: Compound operator to add array elements.

Now, follow this script to get a more comprehensive idea of the above method of declaration:

#! /bin/bash

#array declaration via item assignment
last_name+=(federer nadal roddick)

#print message if no error occurs
echo "last_name is declared when compound assignment happened."
EXPLANATION

In the above script, I made use of the compound += operator to declare the indexed array last_name. In this proceeding, I added 3 elements to the array which automatically declared this new array as it was not extant in the system. Finally, I printed that I completed the array declaration to the terminal using the echo command.

index array declare in bash and create initialize using compound assignment.In this image, the message reflects that I have declared the array with success using the compound assignment technique.

B. Declare an Associative Array in Bash

Likewise, you can accomplish the associative array declaration in Bash using the declare command. This sets the array type explicitly as associative. The super simple command to declare the array is as follows:

declare -A <associative_array_name>
EXPLANATION
  • declare: Bash command used to set the array variable attribute.
  • -A: Option indicating the declaration of an associative array.
  • <associative_array_name>: The name you want to assign to the array.

Furthermore, you can declare an associative array in Bash via value assignment through keys (also called string indices). See the syntax below:

declare -A array_name=([key1]=value1 [key2]=value2… [keyN]=valueN)

At this point, I will declare two associative arrays in the following script to display the methods:

#! /bin/bash

#array declaration using the declare command
declare -A cricket 
echo "associative array cricket is declared"

#array declaration with elements and printing message
declare -A players=([tennis]=fedExpress [cricket]=buzz [football]=cr7)
echo "associative array players is declared"
EXPLANATION

The aforementioned bash script shows that I declared an empty associative array and named it cricket. I used the -A option to notify that I intended to declare a Bash array which is associative in nature. Then, I also declared an array named players and added some values to it. Finally, I printed that I declared the arrays using two echo commands after each line of array declaration.

associative array declaration in bash and create initialize.

This screenshot denotes that I have declared two associative arrays using the script.

Note: Don’t forget to declare an associative array with declare -A command nor Bash will treat it as an indexed array.

Array Creation in Bash

Now that you have grasped the basics of bash array declaration, let me redirect the discussion to creating an array in Bash. Array creation in Bash necessarily revolves around the allocation of memory along with preparing it to hold values. However, one key thing to remember is that the array creation happens simultaneously with the array declaration. Therefore, reviving the declaration concepts will seamlessly introduce you to array creation in Bash and the next section serves that purpose for both the indexed and associative arrays.

A. Create an Indexed Array in Bash

You can create a Bash array in the similar manner you declared them in the former section. Let’s reiterate together. Here, I will mention both the direct and indirect methods.

Method 01: Using Direct Methods to Create an Indexed Array in Bash

The explicit declaration using the declare -a command and array defining with value assignment both fall into the category of direct methods to create an indexed array in Bash. The standard syntaxes are:

Syntax 01:

declare -a <name_of_array>

Syntax 02:

array_name=(item1 item2… itemN)

Now, I will develop a script to create two arrays and print their lengths to show you the gist:

#! /bin/bash

#array creation using syntax -1
declare -a opponents

#printing array length
echo "length of array1 is: ${#opponents[@]}"

#array creation using syntax -2
hello=(world universe multiverse)

#printing array length
echo "length of array2 is: ${#hello[@]}"
EXPLANATION

I used the above bash script to create the arrays opponents and hello. In the first case, I used the declare command to declare and create the array opponents (though empty) at the same time. In the second case, I assigned names as well as values to the hello array. Finally, I printed the array lengths using the echo ${#the_array[@]} (Here, ${} is used to retrieve the value of a variable, the_array is the name of the array you want to assign, and [@] points out the referencing of all elements of the array) expression to state that I created the arrays successfully.

index array creation in bash.In this aforementioned snapshot, the script prints the lengths of two arrays. This represents the creation of Bash arrays indeed.

Method 02: Using the Indirect Method to Create an Indexed Array in Bash

Additionally, you can just assign values to an array of your choice indirectly creating an array. Navigate to the following and utilize the command:

array_name[index]=element
EXPLANATION
  • array_name: The array name of your choice.
  • [index]: Points out the elements at the index.
  • element: the element located at the index.

To develop an array called flowers and print the elements see the below Bash script:

#! /bin/bash

#indirect creation of a bash array
flowers[0]=tulip
flowers[1]=lotus
flowers[2]=rose

#printing the array elements
echo ${flowers[@]}
EXPLANATION

In this script, I directly assigned 3 values to an array that I wished to name flowers using their positional keys (indices). This eventually helped me create the array and I was able to print all the elements using the expression echo ${flowers[@]}.

bash array declaration with creation using item assignment.In this image, you see that I have assigned 3 items (tulip, lotus, rose) to the flowers array that automatically creates the array.

B. Create an Associative array in Bash

In Bash, creating the associative arrays is very straightforward demanding a few lines of code. In the next feature, I will walk you through the several ways you can adopt to create bash associative arrays filling your requirements.

Method 01: Using the Explicit Commands to Create a Bash Associative Array

There are two commands namely declare and typeset that you can make responsible for the Bash associative array creation. Of them, you already have seen the use case of the declare command in bash array declaration. Similarly, syntax using the typeset command is also afoot.

declare -A <array_name>
typeset -A <array_name>

Now, see the below Bash script for more in-depth intuition:

#! /bin/bash
echo "Hello, World!"

#array creation using the declare command and populate with values
declare -A employee
employee[man1]=developer
employee[man2]=tester

#array creation using the typeset command and populate with values
typeset -A employer   
employer[boss1]=CEO
employer[boss2]=CTO

# print message of confirmation
echo "the two associative arrays are created with success"
EXPLANATION

In developing the aforementioned script, I created 2 associative arrays. In the 4th line, I used the declare command while I used the typeset command, in line number 9, and created the arrays employee and employer respectively. Finally, I used the echo commands to show that I created the arrays with success.

associative array creation in bash.In the above-captured image, you notice that I have used both the declare and typeset commands to create associative arrays.

Method 02: Utilizing Item Assignment to Create a Bash Associative Array

Similarly, you can create a Bash associative array through item assignment. It refers to the creation of an array by adding a set of elements in the respective positions using keys (string indices). To implement, simply add the following line and you are good to go:

declare -A array_name=([key1]=value1 [key2]=value2… [keyN]=valueN)

In the following, I will create an array named movies as a quick demonstration:

#! /bin/bash

#creating the array
declare -A actor=([bale]=machinist [depp]=publicEnemies [tobby]=great_gatsby)

#print message if no error occurs
echo "TaDa!, the movies are safe and sound in the array."
EXPLANATION

In this Bash script, I created an associative array using the declare command and simultaneously inserted values using keys (string indices). As a result, this item assignment along with declaring the array explicitly creates the array. Finally, the echo command denotes that the code is correct and I was able to create the array using the item assignment method.

associative array creation in bash using item assignment.This image shows my creation of associative arrays via item assignment.

Array Initialization in Bash

The initialization of a Bash array means setting up its initial values. This you can do at the time of array declaration/creation or later by providing the initial values for the array to store. Now, in this scope, I will shed light on the various ways you can initialize a bash array (both the indexed and associative array) seamlessly. So, let’s dive in.

A. Initialize a Bash Indexed Array

This section revolves around the various tips and tricks you can follow to initialize an indexed array in Bash. Specifically, I have discussed the index-based and loop-based methods for array initialization. So, without delay, let’s jump right in.

Method 01: Using Indices to Initialize an Indexed Array with Elements In Bash

The indexed arrays store values using indices that are 0-based. Now, you can exploit them to initialize the Bash array with elements. This is also referred to as item assignment.  On top of that, due to its vibrant nature, you can initialize elements in places that are not contiguous in the array.

At this point, follow the below script to initialize an array using indices:

#!/bin/bash

# array initialization in the contiguous manner
declare -a topOrder=(tamim liton shanto)

#array initialization using random indices
middleOrder=([2]=shakib [5]=mushi [8]=riyad)

#print message if the initialization is successful
echo "the arrays are initialized"
EXPLANATION

In this script, I initialized two index arrays topOrder and middleOrder with values at the beginning of array creation. Moreover, I initialized the arrays by adding elements both with and without in a sequential manner (array topOrder and middleOrder respectively). Finally, I used the echo command and printed a message to show that I seamlessly initialized arrays.

array declaration in bash with initialization.The aforementioned snap displays that I have initialized two indexed arrays by adding elements in the array at the time of array declaration and creation.

Method 02: Applying for Loop to Initialize an Indexed Array in Bash

Accessing array elements using loops is a very common practice among programmers. However, this technique can also come in handy at the time of array initialization. Therefore, see the below script to loop through an array to initialize it:

#!/bin/bash

# declaring an empty array
declare -a numbers

# looping through the array and initialize with 5 numbers
for ((i=1; i<=5; i++))
do
numbers[$i]=$i 
done 

#print the array
for ((i=1; i<=5; i++)); do
echo "numbers[$i]: ${numbers[$i]}"
done
echo "array is initialized"
EXPLANATION

In this aforestated Bash script, first, I declared and created the array numbers. Then, I used the for loop to iterate the array 5 times and initialize it with 5 values. Finally, The echo command and for loop displayed the initialized values to the terminal.

array declaration in bash with initialization using for loop.The above-mentioned snapshot shows that I have initialized an indexed array using a for loop and added five elements to the array to store.

B. Initialize a Bash Associative Array

Initialization of Bash associative array is possible to achieve in several ways. In the following section, I will mention two methods (using item assignment and for loop).

Method 01: Availing Item Assignment to Initialize an Associative Array in Bash

Using item assignment, you can initialize an associative Bash array. Just after the declaration or the array creation, you have to define the keys and insert values to the keys and you are done.

To create an array called results and initialize it to store values, go through the below script:

#!/bin/bash

#array declaration and value initialization via item assignment
declare -A results=([match1]=won [match2]=lost)

#printing the first item
echo "${results[match1]}"
EXPLANATION

I used the above script to declare an associative array namely results. At the same time, I also populated it with 2 elements. Finally, I printed the 1st initialized element using the expression echo “${results[match1]}”.

associative array initialization using item assignment.In this picture, you spot that I have initialized an associative array by assigning values specifying keys.

Similarly, you can initialize the array later after the declaration:

#!/bin/bash

# Declare an associative array
declare -A my_associative_array

# Initialize the array using item assignment later 
my_associative_array["key1"]="masrur"
my_associative_array["key2"]="value2"
my_associative_array["key3"]="Alam"

#print array elements for verification
echo "${my_associative_array["key1"]}"
echo "${my_associative_array["key3"]}"
EXPLANATION

In this script, I declared the my_associative_array explicitly. Then, I initialized it with 3 values to store as a starting point of data storage. Finally, I utilized the echo command to print 2 values to the terminal.

array initialization after creation.In the attached image, I have printed the array elements that I initialized after the array creation.

Method 02: Employing for Loop to Initialize an Associative Array in Bash

Like indexed arrays, you can also initialize the associative array using a for loop. Below, I will create an array and initialize it via the looping process:

#!/bin/bash

# Declare an associative array
declare -A runs

# Define key-value pairs in an array
keys=("pp1" "pp2" "pp3")
values=("70" "90" "100")

# Initialize the array using a loop
for ((i=0; i<${#keys[@]}; i++)); do
runs[${keys[$i]}]=${values[$i]}
done

# print array elements
echo "${runs[pp1]}"
echo "${runs[pp2]}"
echo "${runs[pp3]}"
EXPLANATION

Here, in this Bash script, I created an associative array namely runs. Then, I created two arrays to store the keys and values of the runs array. After that, I exploited a for loop to assign the keys and the respective values to the array (For every key, the values are stored in the keys and both are sequentially stored in the array runs). Finally, I used the echo command to check for the initialization and I came out successful.

associative array initialization using for loop.In this screenshot, I have shown the initialization of a Bash associative array using a for loop.

Note: In the above, scrutiny lets you discern that creating, declaring, or initializing a Bash array can refer to the same phenomenon which is why the overlapping of methods is strongly visible. In fact, the below lines of code simultaneously declare, create, and initialize Bash arrays.

declare -a array_name=(value)
declare -A arr_name=([key]=value)

Looks familiar, right?

Conclusion

In this article, I have discussed Bash array handling in terms of array declaration, creation, and initialization with values. Moreover, I have attached numerous practical cases through script development. I hope this compact package will aid your learning of Bash arrays and elevate your level of becoming a quality Bash scripter.

People Also Ask

How to initialize an array with elements?

To initialize a bash array, insert elements inside the parentheses like this syntax: my_array=(value).

Do Bash arrays start with 0 or 1?

The Bash arrays, especially, the indexed arrays are 0-index-based arrays means they start with 0. Since their indexing begins with 0 and increments by 1 with each element addition to the arrays.

How to declare an empty array in Bash?

To declare an empty array in Bash, you can use the declare command, simply use the syntax, declare -a/A <array_name>. It creates an empty indexed/associative array and you can assign values later.

Do array declaration and creation differ in Bash?

Yes, in Bash, array declaration and creation are related and often interchangeable. The declaration involves the specification of an array-type variable. This declaration also is responsible for the creation of an array in Bash via dynamically allocating memory.

Is it necessary to declare the array size in Bash?

NO, in Bash, you need not define the array size explicitly. Rather, Bash arrays are dynamic. There is no limitation in terms of adding elements and the length is dynamically adjusted.

How to declare an array in Bash?

To declare an array in Bash, use the syntax: array_name=(element1 element2). This will create an array called array_name with 2 items element1 and element2.

Related Articles


<< Go Back to Bash Array | Bash Scripting Tutorial

Rate this post
Md Masrur Ul Alam

Assalamu Alaikum, I’m Md Masrur Ul Alam, currently working as a Linux OS Content Developer Executive at SOFTEKO. I completed my Bachelor's degree in Electronics and Communication Engineering (ECE)from Khulna University of Engineering & Technology (KUET). With an inquisitive mind, I have always had a keen eye for Science and Technolgy based research and education. I strongly hope this entity leverages the success of my effort in developing engaging yet seasoned content on Linux and contributing to the wealth of technical knowledge. Read Full Bio

Leave a Comment