Home UNIX shell scripting Bourne shell scripting Bash 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:


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



Please enter your comment!
Please enter your name here

error: Content is protected !!