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 ordermacOS 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.
Drop the braces
$dirs[@]expands just$dirs, which means element 0, then adds the literal text[@].
Drills
Answer fast — trust the rule.
With a=(red green blue), what does echo "${a[1]}" print?
With a=(red green blue), what does echo "$a[2]" print?
After a=(red green blue); a+=(yellow), what is ${#a[@]}?
Which expansion passes each folder as exactly one argument, even My Photos?
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 -Aneeds Bash 4 or newer.
