Bash Shell Script Accessing Array Variables

Posted August 31, 2004 by Quinn McHenry in Bourne shell scripting

Last Updated on

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:


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

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.
View more articles by Quinn McHenry

The Conversation

Follow the reactions below and share your own thoughts.

Leave a Reply