Learn/Bash/7. Arrays
Lesson 7 of 8
Sign in

Bash, lesson 7

Arrays

A normal Bash variable holds one string. An array holds many. Bash has two kinds: indexed arrays (a numbered list) and associative arrays (a lookup table from text keys to values).

Indexed arrays

Create one with parentheses, items separated by spaces:

Indexes start at 0. Read an element with ${name[index]}; the braces are required:

Three expansions work on the whole array:

ExpansionGives
"${fruits[@]}"every element, each as a separate word
${#fruits[@]}the number of elements
"${!fruits[@]}"the indexes (or keys)

Loop over the elements with the quoted [@] form, so an element containing a space such as stays in one piece:

2 exercises to try what you just read.

Exercise 1

High scores

Press Ctrl Enter or Check to test your code.

Exercise 2

Bird watching

Press Ctrl Enter or Check to test your code.

blood orange

"${fruits[*]}" (with *) joins all elements into one string, separated by the first character of the special variable IFS, which is a space by default. That is handy for printing an array on one line.

Filling arrays from input

read -a splits one line into an array of words:

mapfile -t (also called readarray) reads all remaining lines into an array, one line per element. -t removes the newline from each line:

Associative arrays

An associative array maps keys to values, like a dictionary. You must declare it first with declare -A:

[[ -v name[key] ]] tests whether a key exists. Looking up a missing key just gives an empty string, which can hide mistakes.

Counting things is a natural fit: (( count[$word]++ )) adds one to the count for word, starting from empty (treated as 0).

The keys come back in no particular order. When the output order matters, sort them. A common way is to print the keys one per line and pipe them through the sort command:

(This simple form assumes the keys contain no spaces.)

unset 'price[tea]' removes one entry; unset price removes the whole array.

Further reading

  • Bash manual: Arrays
  • Bash manual: Bash builtins (read -a, mapfile, declare)

Read one line of whole-number scores separated by spaces into an array. Print the number of scores, the highest score, and all scores in reverse order (last one first) on one line, separated by spaces.

Sample input:

Sample output:

Each input line is the name of a bird you spotted (one word). Count how many times you saw each bird and print one line per bird in alphabetical order, in the form bird: count. Finally print Species: N, the number of different birds.

Sample input:

Sample output:

fruits=(apple pear "blood orange")
echo "${fruits[0]}"      # apple
echo "${fruits[2]}"      # blood orange
echo "${fruits[-1]}"     # the last element: blood orange
fruits[1]="fig"          # replace an element
fruits+=(kiwi)           # append to the end
for f in "${fruits[@]}"; do
    echo "- $f"
done
read -r -a nums          # input: 4 8 15 16
echo "${#nums[@]}"       # 4
mapfile -t lines
echo "Read ${#lines[@]} lines; the first is ${lines[0]}"
declare -A price
price[tea]=220
price[coffee]=280
echo "${price[coffee]}"          # 280
[[ -v price[milk] ]] || echo "no milk"
for key in $(printf "%s\n" "${!count[@]}" | sort); do
    echo "$key: ${count[$key]}"
done
40 95 72 88
Count: 4
Highest: 95
Reversed: 88 72 95 40
robin
sparrow
robin
heron
robin
heron: 1
robin: 3
sparrow: 1
Species: 3