There are quite a few different ways to assign values to arrays. Some are variations on a theme, but there are three main ways to assign values, which are broken down here into “one at a time,” “all at once,” or “by index,” which is partway in between the other two. You can also assign values to an array from a variety of sources, including wildcard expansion and program output.
If the array is declared via the “one at a time” or “all at once” method, the shell automatically detects that an array is being declared. Otherwise, the declare -a myarray statement is necessary to declare to the shell that this variable is to be treated as an array.
One at a Time
The simplest and most straightforward way to set the values of an array is to assign each element one at a time. Just like regular variables, there is no dollar ($) symbol when assigning a value, only when referring to it. At the end of the variable name, the index number goes in square brackets:
numberarray=zero numberarray=one numberarray=two numberarray=three
In addition to its simplicity and clarity, an additional advantage of this form is that you can define sparse arrays. In the following example, there is no third item (“two”) in the array:
numberarray=zero numberarray=one numberarray=three
As with regular variables, you can include spaces in the value, but it will need to be quoted, whether with quotes or a backslash:
country="United States of America" country=United\ Kingdom ...