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.
jan will be stored in reference to zero index, feb to first index, mar to second and apr to fourth.
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.
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 .
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.
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.
It will store the values from 1 to 6 in the array, starting from the zero index .