bash shell script declaring/creating arrays

Posted August 30, 2004 by Quinn McHenry in Bourne shell scripting

Last Updated on

The use of array variable structures can be invaluable. This recipe describes several methods for declaring arrays in bash scripts.

The following are methods for declaring arrays:

names=( Jennifer Tonya Anna Sadie )

This creates an array called names with four elements (Jennifer, Tonya, Anna, and Sadie).

names=( "John Smith" "Jane Doe" )

This creates two array elements, each containing a space.

colors[0] = red
colors[3] = green
colors[4] = blue

This declares three elements of an array using nonsequential index values and creates a sparse array (there are no array elements for index values 1 or 2).

filearray=( `cat filename | tr '\n' ' '`)

This example places the contents of the file filename into an array. The tr command converts newlines to spaces so that multiline files will be handled properly.

names=( "${names[@]}" "Molly" )

This example adds another element to an existing array names.

If anyone has other techniques for creating or adding to arrays, add a comment to this recipe and share the wealth!


About Quinn McHenry

Quinn was one of the original co-founders of Tech-Recipes. He is currently crafting iOS applications as a senior developer at Small Planet Digital in Brooklyn, New York.
View more articles by Quinn McHenry

The Conversation

Follow the reactions below and share your own thoughts.

Leave a Reply