Bash, lesson 7
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).
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:
| Expansion | Gives |
|---|---|
"${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.
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.
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:
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.
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 endfor f in "${fruits[@]}"; do
echo "- $f"
doneread -r -a nums # input: 4 8 15 16
echo "${#nums[@]}" # 4mapfile -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]}"
done40 95 72 88Count: 4
Highest: 95
Reversed: 88 72 95 40robin
sparrow
robin
heron
robinheron: 1
robin: 3
sparrow: 1
Species: 3