Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
167 changes: 64 additions & 103 deletions concepts/arrays/about.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ Bash provides two types of parameters: "scalar" values and arrays.
A scalar value can be a string or a number; it represents a single "thing".

Most of the time, scalar values are sufficient to contain your data.
But sometimes, you need to store a list of scalar values.
Sometimes, you need to store a list of scalar values.
In this case you will use an _array_.

There are two kinds of arrays:
Expand All @@ -14,8 +14,8 @@ There are two kinds of arrays:
* Associative arrays map a string key to a string value.
(Other languages might call this a "map" or a "dictionary".)

The first few sections of this document will cover numerically-indexed arrays (hereafter simply known as "arrays").
Details about associative arrays will show up at the end.
This document covers numerically-indexed arrays (hereafter simply known as "arrays").
Associative arrays will be discussed later.

~~~~exercism/caution
Bash arrays can _only_ store scalar values.
Expand Down Expand Up @@ -45,21 +45,28 @@ myarray=(
)
```

Assigning a list of strings to an array variable in this manner will store the first string at index zero, the next string at index one, the next at index two, and so on.
Assigning a list of strings to an array variable in this manner will store the first string at **index zero**, the next string at index one, the next at index two, and so on.

It is possible to initialize a "sparse array" by specifying the indices you need.
Bash arrays do not need to use consecutive indices.
A "sparse array" is one with gaps in its indices: some positions have a value, and the positions between or before them do not exist at all.
A missing element is not the same as an element holding an empty string.
It is possible to initialize a sparse array by specifying the indices you need.

```bash
raindrops=([3]="Pling" [5]="Plang" [7]="Plong")
```

This array has only three elements, at indices 3, 5 and 7.
There are no elements at indices 0, 1, 2, 4 or 6, so `"${#raindrops[@]}"` (the number of elements) is 3, not 8.

~~~~exercism/note
To reiterate: array indices are zero-based.
This snippet outputs "true":
This snippet outputs "one":

```bash
myarray=("one" "two" "three")
[[ "${myarray[0]}" == "one" ]] && echo true || echo false
echo "${myarray[0]}"
# => one
```
~~~~

Expand All @@ -73,7 +80,7 @@ It is more idiomatic to just assign a (perhaps empty) parenthesized list to init

## Accessing Elements of an Array

As you saw in the note above, the syntax to access an array element is `${myarray[$index]}`.
As you saw in the note above, the syntax to access an array element is `${myarray[index]}`.
The index is given in square brackets.
The curly braces are required.

Expand All @@ -95,7 +102,30 @@ echo "${myarray[i]}"
[arithmetic]: https://www.gnu.org/software/bash/manual/bash.html#Shell-Arithmetic
~~~~

If the given index does not exist in the array, the result of the expansion is an empty string.
If the given index does not exist in the array, the result of the expansion is **an empty string**, not an error.

### Checking whether an Element Exists

To check whether an element exists, use the `-v` test in a conditional command (see the [Conditionals][conditionals] concept).
This distinguishes a missing element from an element that holds an empty string.

```bash
myarray=(one "" three)

if [[ -v myarray[1] ]]; then
echo "index 1 is set"
else
echo "index 1 is not set"
fi
# => index 1 is set

if [[ -v myarray[5] ]]; then
echo "index 5 is set"
else
echo "index 5 is not set"
fi
# => index 5 is not set
```

## Assigning to an Array

Expand All @@ -111,10 +141,28 @@ To _append_ to an array, use the `+=` concatenating-assigment operator, and use
myarray+=("new element 1" "new element 2")
```

## Removing an Element

To remove an element, use the `unset` command.
Quote the argument so the shell does not try to expand the brackets as a filename pattern.

```bash
myarray=(x y z)
unset 'myarray[1]'
declare -p myarray
# => declare -a myarray=([0]="x" [2]="z")
```

The remaining elements are **not** renumbered.
Removing an element from the middle leaves a gap, so the array becomes a sparse array.
Comment thread
glennj marked this conversation as resolved.
Resolved
The length is now 2, but the indices are 0 and 2.

To remove the entire array, give `unset` the name without brackets: `unset myarray`.

## Iterating over an Array

You will typically need to iterate over the _values_ of an array.
Use a for loop (that you saw in the [Looping][looping] concept):
Use a for loop (discussed in the [Looping][looping] concept):

```bash
myarray=("one" "two" "three")
Expand All @@ -133,11 +181,11 @@ for value in "${myarray[0]}" "${myarray[1]}" ... "${myarray[n]}"

The `"${myarray[@]}"` form works with sparse arrays, expanding to only defined values.

This special expansion, where the index is an ampersand (`@`), is only special within double quotes.
This special expansion, where the index is an "at sign" (`@`), is **only special within double quotes**.

#### Other Special Parameter Exapansions
#### Other Special Parameter Expansions

Here are another couple of bits of special syntax that we need for iterating over an array.
Here is more special syntax that we use for iterating over an array.
These are described in the manual in [Shell Parameter Expansion][man-expn].

To find the _length_ of an array, use `${#myarray[@]}`, with a `#` before the name.
Expand All @@ -154,7 +202,8 @@ There are a couple of ways to do this.
1. When you know the indices form an uninterrupted sequence, you can use an _arithmetic_ for loop.

```bash
for ((i = 0; i < ${#myarray[@]}; i++)); do
len=${#myarray[@]}
for ((i = 0; i < len; i++)); do
echo "$i -> ${myarray[i]}"
done
```
Expand Down Expand Up @@ -190,94 +239,6 @@ This outputs the contents with canonical shell quoting.
declare -a a=([0]="the 'first' element" [1]="second" [2]="third" [3]="the \"last\" element")
```

## Associative Arrays

To reiterate, associative arrays use strings for indices, not numbers.
Everything written above applies for associative arrays, but with small differences.
Generally, we use the term "key" not "index": associative arrays map keys to values.

### Declaring an Associative Array

Unlike arrays, associative arrays **must** be declared.
Use the `-A` option to `declare` (or `local` in a function):

```bash
declare -A mymap

myfunc() {
local -A my_local_map
# ...
}
```

### Initializing an Associative Array

The key-value pairs are specified within the parenthesized list:

```bash
mymap=([first]=foo [second]=bar [third]=baz)
declare -p mymap
```

This outputs:

```
declare -A mymap=([second]="bar" [first]="foo" [third]="baz")
```

~~~~exercism/note
Be aware that associative arrays are **unordered**.
~~~~

The declaration and initialization can happen in one line.

```bash
declare -A mymap=([first]=foo [second]=bar [third]=baz)
```

In recent Bash versions, the initialization can use a `(key value key value ...)` list.

```bash
declare -A mymap=(first foo second bar third baz)
```

### Accessing Values

The same syntax as before is used to access elements: `${mymap[$key]}`.

Associative array keys are not evaluated in an arithmetic context.
The usual parameter expansion syntax is required.

### Assigning to an Associative Array

Assignment uses the same syntax as before:

```bash
mymap[$key]="$value"
```

### Iterating

You can use a `for value in "${mymap[@]}"` loop to iterate.
However, you typically also want the key to go along with the value.

Use the `"${!mymap[@]}"` syntax we saw above.

```bash
for key in "${!mymap[@]}"; do
echo "$key -> ${mymap[$key]}"
done
```

This outputs

```
second -> bar
first -> foo
third -> baz
```

To re-emphasize, there is no order to the keys.

[conditionals]: https://exercism.org/tracks/bash/concepts/conditionals
[looping]: https://exercism.org/tracks/bash/concepts/looping
[man-expn]: https://www.gnu.org/software/bash/manual/bash.html#Shell-Parameter-Expansion
Loading
Loading