HomeUNIX shell scriptingBourne shell scriptingbash shell script declaring/creating arrays

bash shell script declaring/creating arrays

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!

Quinn McHenry
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.
RELATED ARTICLES

15 COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments

error: Content is protected !!