bash shell script accessing array variables

Contributor Icon Contributed by qmchenry Date Icon August 31, 2004  
Tag Icon Tagged: Bourne shell scripting

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:

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:

${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:

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

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

${#names[@]} -> 6

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

${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).

Previous recipe | Next recipe |
 
  • anwarhossain
    I think it is a first class tutorial on shell scripting for array.the way of description is so nice.thank u vary muvh
blog comments powered by Disqus