O'Reilly logo

Linux in a Nutshell, 6th Edition by Robert Love, Stephen Figgins, Ellen Siever, Arnold Robbins

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required