Arrays and associative arrays
Hold lists safely in indexed arrays, count by key with associative arrays, and see why macOS's Bash 3.2 lacks associative arrays and mapfile.
Loops - for, while and untilParameter expansionFunctions, arguments and scopeReading input and here documents
Arrays and associative arrays
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- An array holds separate words, so it keeps `b c.log` as one item where a string variable would be split. Create one with `name=(a b c)` and add with `name+=(d)`.
- Always expand with `"${name[@]}"` to get one word per element. `${#name[@]}` is the count and `${!name[@]}` lists the indices.
- `$name` with no index is only element 0, and unquoted `${name[@]}` re-splits on whitespace. ShellCheck flags both.
- `declare -A map` makes an associative array with string keys, useful for counting by key. It needs Bash 4.
- On macOS's `/bin/bash` 3.2, `declare -A` fails with a warning and the script keeps running with an indexed array, so non-numeric keys silently collapse to index 0.
A string is the wrong container for a list
Say you want to collect file names and pass them to a command later. The obvious move is a string: files="a.log b c.log d.log". It fails the moment a name contains a space, because the only record of where one name ends is the whitespace you can’t tell apart from the space inside b c.log. You met this problem in the splitting lesson.
An array keeps the boundaries. It’s a variable holding an ordered list of separate words. That’s the container you want any time you build up a list of arguments, files or lines.
Indexed arrays
$ files=(a.log "b c.log" d.log)
$ echo "count: ${#files[@]}, second: ${files[1]}"
count: 3, second: b c.log
$ printf '<%s>\n' "${files[@]}"
<a.log>
<b c.log>
<d.log>
Indexes start at 0. ${#files[@]} is the number of elements, and "${files[@]}" expands to one word per element, which is the form you’ll use almost every time. Add with +=, take a slice with an offset and length, and list the indices with !:
after +=: 4, last: e.log, slice: b c.log d.log
indices: 0 1 2 3
Those lines are from my test script, from files+=(e.log), ${files[-1]}, ${files[*]:1:2} and ${!files[@]}. unset 'files[0]' removes an element and leaves a gap, so the indices became 1 2 3, not 0 1 2. Don’t assume the indices are contiguous.
A very practical use is building a command from parts, so each argument stays whole. args=(-n 2 logs/access.log) then ./logsum "${args[@]}".
The easy mistakes
Three expansions look right and aren’t. After unset 'files[0]':
bare $files is the first element: []
unquoted splits:
<b>
<c.log>
<d.log>
$files with no subscript means ${files[0]}, which I had just removed, so it printed nothing. And the unquoted ${files[@]} split b c.log into two words. ShellCheck reported both: SC2128, “Expanding an array without an index only gives the first element”, and SC2068, “Double quote array expansions to avoid re-splitting elements”. It also flagged my echo "indices: ${!files[@]}" as SC2145, which warns about mixing a string and an array in one argument. In real scripts, use "${files[*]}" for a single joined string.
To read lines into an array, use mapfile -t lines < file, which gave me six lines from the people file. mapfile (also called readarray) is Bash 4. On macOS’s /bin/bash 3.2 it reports mapfile: command not found. Negative indices like ${files[-1]} are also newer than 3.2, which printed “bad array subscript”. A while read loop works on both.
Associative arrays: counting by key
An indexed array maps position numbers to values. An associative array maps string keys to values, like a dictionary. You must declare it with declare -A, so Bash knows the keys are strings.
Here is logsum version 7. It counts requests for each status code, which is the job sort | uniq -c did earlier, but with the totals held in the script:
#!/usr/bin/env bash
# logsum v7: count requests per status code with an associative array
declare -A count
while read -r status; do
count[$status]=$(( ${count[$status]:-0} + 1 ))
done < <(awk '{ print $8 }' "${1:-logs/access.log}")
for status in "${!count[@]}"; do
printf '%s %d\n' "$status" "${count[$status]}"
done | sort
$ ./logsum
200 104
301 16
304 24
403 16
404 16
500 24
These match the uniq -c totals from the earlier streams lessons. ShellCheck reported nothing. The key line is count[$status]=$(( ${count[$status]:-0} + 1 )): read the current count with a default of 0, add one, store it back. Iteration order of an associative array isn’t defined, so the output goes through sort.
Other operations I ran: setting a key (age[grace]=85), testing for one with [[ -v age[ken] ]] (false, so it printed “ken is not a key”), and removing one with unset 'age[linus]', which dropped the count from 3 to 2.
The Bash 3.2 trap
Associative arrays arrived in Bash 4, and macOS still ships 3.2. What makes this one dangerous is that the script doesn’t stop. On /bin/bash:
$ /bin/bash -c 'declare -A m; m[apple]=1; m[banana]=2; echo "entries: ${#m[@]}, apple=${m[apple]}"'
/bin/bash: line 0: declare: -A: invalid option
declare: usage: declare [-afFirtx] [-p] [name[=value] ...]
entries: 1, apple=2
declare -A complained and the script carried on, with m as an ordinary indexed array. Inside [...], an indexed array evaluates the key as arithmetic, so apple and banana both become 0, and the second assignment overwrote the first. My logsum happened to produce correct output on 3.2 because status codes are numeric, so each one is a valid index, but a script keyed by words would silently count wrong. If your script needs these features, require them at the top. A line such as ((BASH_VERSINFO[0] >= 4)) || { echo "needs bash 4+" >&2; exit 1; } fails fast. I didn’t run that exact guard on 3.2, but the BASH_VERSINFO array is the standard way to read the version.
About the video
“Arrays in Bash Explained in 7 Minutes! - Indexed, Associative, and Nested / Multi-Dimensional” is by Dave Eddy of You Suck at Programming, 7 minutes 10 seconds, from March 2025. The title lists indexed, associative and nested arrays, so it should cover the same ground as this lesson plus the multi-dimensional workaround. The description is only links and I had no transcript, so I haven’t checked that. It is in English. It was the only array video I found that was short, recent and embeddable, so there’s no runner-up.
Where this fits
Now you can hold data in a script reliably. Next comes making the script refuse to continue when something goes wrong: strict mode with set -e, -u and pipefail.
Check yourself
Why use an array instead of a string such as `files="a.log b c.log"`?
A string splits on whitespace when expanded, so `b c.log` becomes two items. An array stores each element as its own word, and `"${files[@]}"` preserves them.
What is the difference between `"${arr[@]}"` and `${arr[@]}`?
The quoted form yields one word per element. The unquoted form splits and globs each element again, so elements with spaces fall apart.
You run a script that uses `declare -A` on a stock Mac and get one entry for all keys. Why?
`/bin/bash` 3.2 doesn't support associative arrays. `declare -A` prints an error, and later `m[apple]=1` treats `apple` as arithmetic, which is index 0.
How do you loop over every key of an associative array `count`?
`for key in "${!count[@]}"; do ... "${count[$key]}"; done`. The `!` gives the keys, and the order is not guaranteed, so pipe to `sort` if order matters.
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.