Skip to the workspace
Pebellslearn by building
Variables and Data  ›  Lesson

Arrays and Associative Arrays

Arrays 14 minAn indexed array holds a numbered list of strings, expanded safely as "${arr[@]}", and an associative array declared with declare -A maps string keys to values.

shell bash / Arrays and Associative Arrays

Explore each scene at your own pace.

01 · The rule

The rule

Arrays and Associative Arrays

An indexed array holds a numbered list of strings, expanded safely as "${arr[@]}", and an associative array declared with declare -A maps string keys to values.

Preserve element boundaries when reading indexed and associative arrays.

backup.sh should now archive three folders, and one of them is My Photos. If you store them in a single string separated by spaces, that space inside the name will split one folder into two. An array keeps each item whole.

The rule

Store lists in arrays; expand them with "${arr[@]}".

Indexed arrays are numbered lists, starting at 0:

dirs=("$HOME/notes" "$HOME/My Photos" "$HOME/code")

echo "${dirs[0]}"        # first element
echo "${#dirs[@]}"       # how many: 3
dirs+=("$HOME/music")    # append one more
tar -czf "$archive" "${dirs[@]}"   # every element, each one argument
  • "${dirs[@]}" expands to every element, each as a separate word, spaces preserved.
  • ${#dirs[@]} is the number of elements.
  • "${!dirs[@]}" lists the indexes (0, 1, 2 …).

Associative arrays (Bash 4 and later) use string keys instead of numbers. You must declare them first:

declare -A keep
keep[daily]=7
keep[weekly]=4
echo "${keep[weekly]}"      # 4
echo "${!keep[@]}"          # the keys, in no guaranteed order

macOS still ships the old Bash 3.2, which has indexed arrays but not declare -A; install a newer Bash if you need them there.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.