Arrays

Bash supports one-dimensional arrays. Elements are referenced by an index; the first element is numbered 0 and there is no upper limit on the number of elements. Arrays are initialized with a special form of assignment:

message=(hi there how are you today)

where each value (in this example, each word) becomes an element of the array.

Elements may also be assigned individually:

message[0]=hi            This is the hard way
message[1]=there
message[2]=how
message[3]=are
message[4]=you
message[5]=today

Declaring arrays is not required. Any valid reference to a subscripted variable can create an array.

Bash also provides associative arrays, where the indices are strings instead of numbers. In this case, [ and ] act like double quotes. Associative arrays are created with declare -A arrayname. Unlike indexed arrays, when assigning a value to an associative array, a subscript is always required.

When referencing arrays, use the ${ ... } syntax. This isn’t needed when referencing arrays inside (( )) (the form of let that does automatic quoting). Note that [ and ] are typed literally (i.e., they don’t stand for optional syntax).

Syntax

Effect

${ name[ i]}

Use element i of array name. i can be any arithmetic expression as described under let.

${ name}

Use element 0 of indexed array name.

${ name[*]}, ${ name[@]}

Use all elements of array name.

${# name[*]}, ${# name[@]}

Use the number of elements in array name.

The built-in commands declare, local, and readonly accept the -a option for an indexed array and the ...

Get Linux in a Nutshell, 6th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.