The Ops Community ⚙️

Tarush Arora
Tarush Arora

Posted on

How to Declare and Add Value in Bash Array

Head Image

How to Declare Bash Array?

By using the declare command, you can declare both indexed and associative array in the Bash.

Let’s look at its syntax.

For declaring the indexed array, you have to run the declare -a name_of_array command.

Here, declare is the keyword.
-a is option to create indexed array
,and name_of_array is the name of your array.

Declare

For Example: To declare an indexed array with name Linux, you have to use the following command:

declare -a Linux

You can assign any name to the array, as per your requirement.
However, it must have underscore sign, if there are multiple strings in the name.

For Example: To declare an array with name Linux my OS, you have to use the following command:

declare -a Linux_my_OS

Further, for declaring the associative array, there’s only slight difference between the command.

declare -A name_of_array is the command for creating an associative array.

Declare -A

You only have to change the option from small a to capital A.

For Example: To declare an associative array with name Linux and Linux my OS, you will run the following command:

declare -A Linux
declare -A Linux_my_OS

Adding Values in Bash Array

Once you have declared the array, its time to store some values in it.

Bash provides multiple ways to put values in the array and allows to add both numerical, alphabetical strings and combination of both in the array.

Let’s have look at it.

my_array=(1 2 3 4) command is used to add numerical value in the array with name my_array.

Once this command gets successfully executed, 1, 2, 3, and 4 gets stored in the array.

Add 1

You can put any value of your choice.

For Example: To put values 10, 20, 30 and 40 in the array with name Linux, you will run the following command:

Linux=(10 20 30 40)

To store string value in the array, you can follow the same command and write string value instead of numeric.

Add

For Example: To add string value Jan, Feb, Mar and April in the array with name Linux, you have to run the following command:

Linux=(Jan Feb Mar April)

It will store the string values in your array.

To be Continued

Top comments (0)