O'Reilly logo

The Linux Command Line by William E. Shotts Jr.

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Creating an Array

Array variables are named just like other bash variables and are created automatically when they are accessed. Here is an example:

[me@linuxbox ˜]$ a[1]=foo
[me@linuxbox ˜]$ echo ${a[1]}
foo

Here we see an example of both the assignment and access of an array element. With the first command, element 1 of array a is assigned the value foo. The second command displays the stored value of element 1. The use of braces in the second command is required to prevent the shell from attempting pathname expansion on the name of the array element.

An array can also be created with the declare command:

[me@linuxbox ˜]$ declare -a a

Using the -a option, this example of declare creates the array a.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required