Anchor(faq5)

How can I use array variables?

BASH and KornShell already have one-dimensional arrays indexed by a numerical expression, e.g.

The indexing always begins with 0.

The awkward expression  ${#host[@]}  returns the number of elements for the array host. Also noteworthy is the fact that inside the square brackets, i++ works as a C programmer would expect. The square brackets in an array reference force an ArithmeticExpression.

It's possible to assign multiple values to an array at once, but the syntax differs from Bash to KornShell:

Bash also lets you initialize an array using a [:glob:]:

Using array elements en masse is one of the key features. Much like "$@" for the positional parameters, "${arr[@]}" expands the array to a list of words, one array element per word, even if the words contain internal whitespace. For example,

If one simply wants to dump the full array, "${arr[*]}" will cause the elements to be concatenated together, with the first character of IFS (a space by default) between them.

BASH's arrays are also sparse. Elements may be added and deleted out of sequence.

BASH 3.0 added the ability to retrieve the list of index values in an array, rather than just iterating over the elements:

[:BashFAQ#faq73:Parameter Expansions] may be performed on array elements en masse as well:

Parameter Expansion can also be used to extract elements from an array:

The @ array (the array of positional parameters) can be used just like any regularly named array.

For examples of loading data into arrays, see [:BashFAQ#faq1:FAQ #1]. For examples of using arrays to hold complex shell commands, see [:BashFAQ#faq50:FAQ #50] and [:BashFAQ#faq40:FAQ #40].