Um momento
0xE0Lesson 15 of 18

Arrays and associative arrays

Store lists in indexed arrays and key-value pairs in associative arrays.

24 min 7-question quiz 2 code exercises
By the end of this lesson you can
  • Create, index, extend and loop over indexed arrays safely
  • Load lines into an array with mapfile
  • Count and look things up with associative arrays

A string can hold a list only until an item contains a space. Arrays hold each item separately:

SyntaxMeans
crew=(Ada "Grace Hopper" Linus)create
${crew[1]}one element (indexes start at 0) → Grace Hopper
"${crew[@]}"every element, each as its own word
${#crew[@]}how many → 3
crew+=(Ken)append
"${!crew[@]}"the indexes → 0 1 2 3
"${crew[@]:1:2}"a slice: 2 elements from index 1
unset 'crew[0]'remove one element

As with "$@", the quotes around "${crew[@]}" are what keep Grace Hopper in one piece.

arrays.sh
1crew=(Ada "Grace Hopper" Linus)
2crew+=(Ken)
3echo "${#crew[@]} aboard; second is ${crew[1]}; last is ${crew[-1]}"
4for member in "${crew[@]}"; do echo "- $member"; done
5for i in "${!crew[@]}"; do printf '%d=%s ' "$i" "${crew[i]}"; done
6echo
7echo "Shift B: ${crew[*]:2}"
Output
4 aboard; second is Grace Hopper; last is Ken
- Ada
- Grace Hopper
- Linus
- Ken
0=Ada 1=Grace Hopper 2=Linus 3=Ken 
Shift B: Linus Ken

mapfile -t lines < file (also spelled readarray) reads every line of a file or stream into an array in one go; -t strips the newlines. Combine it with process substitution to capture a command’s output: mapfile -t logs < <(find . -name "*.log").

mapfile.sh
1mapfile -t checklist <<'EOF'
2seal airlock
3check oxygen
4start engines
5EOF
6echo "${#checklist[@]} steps, the last: ${checklist[-1]}"
7for (( i = ${#checklist[@]} - 1; i >= 0; i-- )); do
8  echo "undo step $(( i + 1 )): ${checklist[i]}"
9done
Output
3 steps, the last: start engines
undo step 3: start engines
undo step 2: check oxygen
undo step 1: seal airlock

Associative arrays: look things up by name

An associative array maps string keys to values - a dictionary. Declare it first with declare -A:

1declare -A fuel=([deck1]=80 [deck2]=45)
2fuel[deck3]=12                 # add or update
3echo "${fuel[deck2]}"           # look up → 45
4echo "${!fuel[@]}"              # the keys (in no particular order!)
5[[ -v fuel[deck9] ]] || echo "no deck9"   # does a key exist?

Counting is a one-liner: (( count[$word]++ )). Keys come back in an arbitrary order, so pipe the results through sort.

tally.sh
1declare -A visits
2for name in ada ken ada grace ada ken; do
3  (( visits[$name]++ ))
4done
5for name in "${!visits[@]}"; do
6  echo "${visits[$name]} $name"
7done | sort -k1,1nr -k2,2
8echo "Has linus visited? ${visits[linus]:-no}"
Output
3 ada
2 ken
1 grace
Has linus visited? no

Key takeaways

  • Create arrays with (a b c), read with "${arr[@]}", count with ${#arr[@]}, append with +=.

  • Quote "${arr[@]}" to keep each element intact; arrays are the safe way to build argument lists.

  • mapfile -t arr < file loads lines into an array.

  • declare -A makes a key-value map; (( count[$key]++ )) tallies anything.

Lesson quiz

7 questions · pass with 5 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: write Bash scripts

Write a script in the editor and run it for real against sample input. Each run gets a fresh Linux sandbox with Bash 5.2 and the GNU tools on Wandbox, a free public service - so experiment freely, even with rm. Your script and test input are sent there.

Exercise 1

Reverse the checklist

+25 XP

stdin is a launch checklist, one step per line. Shutting down means doing it backwards. Load the lines into an array, then print them in reverse order, numbered with their original step number:

3. start engines
2. check oxygen
1. seal airlock
  • Three steps
  • One step
script.sh
Loading editor…

Your script runs with Bash 5.2 and GNU tools on Wandbox, a free public service, in a fresh sandbox each time. Your script and test input are sent to that service.

Exercise 2

Radio chatter word tally

+25 XP

stdin is radio chatter. Count how often each word appears (words are separated by spaces; treat upper and lower case the same by lower-casing everything). Print count word for every word, most frequent first, ties broken alphabetically. Use an associative array.

  • Chatter
  • Short
script.sh
Loading editor…

Your script runs with Bash 5.2 and GNU tools on Wandbox, a free public service, in a fresh sandbox each time. Your script and test input are sent to that service.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…

Gostou da aula? 😆👍
Apoie nosso trabalho com uma doação: