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:09:04 PM



Title: bash shell script accessing array variables
Post by: Mark David on March 16, 2007, 01:09:04 PM
bash shell script accessing array variables

The bash shell allows a number of methods for accessing elements of variable arrays. This recipe demonstrates some of these techniques.

Given the array defined by the following code:

Code:
names=( Jennifer Tonya Anna Sadie Molly Millie)

The individual elements in the array can be accessed by their numeric index (remember that they start counting a zero) with:

Code:
${names[0]}  -> Jennifer 
${names[3])  -> Sadie

All of the elements can be accessed at the same time (which is useful in a for loop) with the following:

Code:
${names[@]} 
${names[*]}

The number of elements in the array can be obtained with:

Code:
${#names[@]}  -> 6

A range of elements can easily be specified with the following syntax:

Code:
${names[@]:2:3}  -> Anna Sadie Molly 
${names[@]:3}  ->  Sadie Molly Millie

The first example starts at element 2 (the third element) and returns the next three elements (:2:3). The second example starts at record 3 and returns all of the remaining records (:3).