Techno World Inc - The Best Technical Encyclopedia Online!

THE TECHNO CLUB [ TECHNOWORLDINC.COM ] => Shell Script => Topic started by: Mark David on March 16, 2007, 01:17:08 PM



Title: bash shell script declaring/creating arrays
Post by: Mark David on March 16, 2007, 01:17:08 PM
bash shell script declaring/creating arrays

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

The following are methods for declaring arrays:

Code:
names=( Jennifer Tonya Anna Sadie )

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

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

This creates two array elements, each containing a space.

Code:
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).

Code:
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.

Code:
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!