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]=todayDeclaring 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 |
|---|---|
${
| Use element
|
${
| Use element 0 of
indexed array |
${
| Use all elements of
array |
${#
| Use the number of
elements in array
|
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.
Read now
Unlock full access