Anchor(faq5)

How can I use array variables?

BASH and KornShell 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 for BASH 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. (That shortcut does not work in ksh88.)

It's possible to assign multiple values to an array at once, but the syntax differs across shells.

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

Using array elements en masse is one of the key features. In exactly the same way that "$@" is expanded for positional parameters, "${arr[@]}" is expanded to a list of words, one array element per word. For example,

This works even if the elements contain whitespace. You always end up with the same number of words as you have array elements.

If one simply wants to dump the full array, one element per line, this is the simplest approach:

For more complex array-dumping, "${arr[*]}" will cause the elements to be concatenated together, with the first character of IFS (or a space if IFS isn't set) between them. As it happens, "$*" is expanded the same way for positional parameters.

BASH and Korn shell 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:

Bash's [:BashFAQ/073: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.

If you wish to append data to an existing array, there are several approaches. The most flexible is to keep a separate index variable:

If you don't want to keep an index variable, but you happen to know that your array is not sparse, then you can use the highest existing index:

If you don't know whether your array is sparse or not, but you don't mind re-indexing the entire array (and also being very slow), then you can use:

If you're in bash 3.1 or higher, then you can use the += operator:

For examples of loading data into arrays, see [:BashFAQ/001:FAQ #1]. For examples of using arrays to hold complex shell commands, see [:BashFAQ/050:FAQ #50] and [:BashFAQ/040:FAQ #40].