LESSON · 1 OF 5

Indexed arrays

Indexed arrays

Bash supports two array types: indexed (numeric keys) and associative (string keys). Indexed arrays are the everyday one.

Declaring

bash
fruits=(apple banana cherry)

fruits[3]="date"       # set by index
fruits+=(elderberry)   # append with +=

Space-separated inside parentheses. Or built up one element at a time.

Accessing elements

bash
echo "${fruits[0]}"     # apple (arrays are zero-indexed)
echo "${fruits[1]}"     # banana
echo "${fruits[-1]}"    # elderberry (negative index counts from end)

The ${...} braces are required. $fruits[0] doesn't work.

All elements at once

bash
echo "${fruits[@]}"     # every element as separate words
echo "${fruits[*]}"     # every element joined with IFS

Same @ vs * distinction as $@ vs $* from the arguments topic. Almost always use [@].

Length

bash
echo "${#fruits[@]}"    # 5 (number of elements)
echo "${#fruits[0]}"    # 5 (length of the first element's string)

Notice: ${#arr[@]} counts elements. ${#arr[0]} counts characters in the first element.

Iterating

bash
for fruit in "${fruits[@]}"; do
  echo "processing $fruit"
done

Always quote "${arr[@]}". Same reason as "$@": it preserves element boundaries when values contain spaces.

Spin up a fresh environment and practice live.
linux-devops-basic · fresh machine · ready in under a minute