Skip to Content
Linux in a Nutshell, 6th Edition
book

Linux in a Nutshell, 6th Edition

by Ellen Siever, Stephen Figgins, Robert Love, Arnold Robbins
September 2009
Beginner
942 pages
85h 34m
English
O'Reilly Media, Inc.
Content preview from Linux in a Nutshell, 6th Edition

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Unix in a Nutshell, 4th Edition

Unix in a Nutshell, 4th Edition

Arnold Robbins
Linux Under the Hood

Linux Under the Hood

Sander van Vugt
Linux Kernel in a Nutshell

Linux Kernel in a Nutshell

Greg Kroah-Hartman

Publisher Resources

ISBN: 9780596806088Errata Page