Bash supports two array types: indexed (numeric keys) and associative (string keys). Indexed arrays are the everyday one.
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.
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.
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 [@].
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.
for fruit in "${fruits[@]}"; do
echo "processing $fruit"
done
Always quote "${arr[@]}". Same reason as "$@": it preserves
element boundaries when values contain spaces.