HomeUNIX shell scriptingBourne shell scriptingBash Shell Script Accessing Array Variables

Bash Shell Script Accessing Array Variables

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

Quinn McHenry
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.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

LATEST REVIEWS

Recent Comments

error: Content is protected !!