The Ops Community

Tarush Arora
Tarush Arora

Posted on

How to Declare and Add Value in Bash Array: Continued

Further, array always stores the values in reference to index. Index can be defined as the position in the array.

The first value you enter in the add command is stored with reference to the zero index, which is the first position in array.

In Bash, you can also define the index, while adding the values.
For Example: Let’s add strings values, jan, feb, mar and apr in the my_array by defining the index.

By executing the following command, all the string values will get stored in the my_array.

bash 1

jan will be stored in reference to zero index[0], feb to first index[1], mar to second[2] and apr to fourth[4].

If you find it complex to add all the values at once, you can add them one by one, by running the below bash command.

bash 2

You always have to put the value between the upper commas ‘ ‘.
For associative arrays, bash offers an additional feature to have a string in the place of default index values.

For Example: If you want to add values in reference to index with string values instead of 0, 1, 2, etc., then you have to declare the associative array.

In the following command, my_array is the associative array name and its first index value is [first] instead of [0].

bash 3

You can put any string in the place of [first], [second], and so on.

For example: To create an array with index value of AAA, BBB and CCC, you will use the below commands:

declare -A my_array

In addition, you can also add all the values at once, by running the command according to below syntax.

bash 4

Besides the numeric and string index, you can add sequential values to a bash array by writing a single command.

For Example: For adding values from 1 to 6, you will run the command using seq keyword.

bash 5

It will store the values from 1 to 6 in the array, starting from the zero index [0].

Discussion (0)