Bash Shell Script Accessing Array Variables
Posted by Quinn McHenry in Bourne shell scripting
The bash shell allows a number of methods for accessing elements of variable arrays. This tech-recipe demonstrates some of these techniques.
Take, for example, 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.) This can be seen with the following:
${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 the following:
${#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).
About Quinn McHenry
View more articles by Quinn McHenry
The Conversation
Follow the reactions below and share your own thoughts.
October 26, 2009 at 10:01 pm, Anonymous said:
I think it is a first class tutorial on shell scripting for array.the way of description is so nice.thank u vary muvh
July 21, 2011 at 1:18 pm, Contact Ashugupta said:
Nice