Assigning Arrays

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[0]=zero 
numberarray[1]=one
numberarray[2]=two
numberarray[3]=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[0]=zero 
numberarray[1]=one
numberarray[3]=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[0]="United States of America" country[1]=United\ Kingdom ...

Get Shell Scripting: Expert Recipes for Linux, Bash, and More now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.