Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
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.

Arrays 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.

The shortcut

Every array expansion needs three marks: quotes, braces, @. Say it as you type: quote, brace, at.

What each mark in "${dirs[@]}" doesStep 1 of 4
  1. Drop the braces

    $dirs[@] expands just $dirs, which means element 0, then adds the literal text [@].

Drills

Answer fast — trust the rule.

quick drill

With a=(red green blue), what does echo "${a[1]}" print?

quick drill

With a=(red green blue), what does echo "$a[2]" print?

quick drill

After a=(red green blue); a+=(yellow), what is ${#a[@]}?

quick drill

Which expansion passes each folder as exactly one argument, even My Photos?

quick drill

What does declare -A give you that a plain array does not?

Remember

  • Store lists in arrays; expand them with "${arr[@]}".
  • Quote, brace, at: all three, every time. ${#arr[@]} counts.
  • Trap: $arr[1] is element 0 plus text; declare -A needs Bash 4 or newer.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainBack up a list of folders

Change backup.sh so it archives three folders, one of which is called My Photos. Show how you store the list, how you pass it to tar, and how you print how many folders there are. Explain why each mark in "${dirs[@]}" is needed.