How to use bash arrays and associative arrays

· Category: Linux

Short answer

Bash supports indexed arrays and associative arrays (dictionaries) for structured data manipulation.

Steps

  1. Indexed array:
fruits=("apple" "banana" "cherry")
echo "${fruits[0]}"
  1. Iterate:
for f in "${fruits[@]}"; do echo "$f"; done
  1. Associative array:
declare -A user
user[name]="Alice"
user[age]=30
echo "${user[name]}"

Tips

  • Use [@] to expand all elements; [*] joins them into one string.
  • ${#array[@]} gives the element count.
  • Associative arrays require bash 4+.

Common issues

  • Forgetting declare -A for associative arrays causes unexpected behavior.
  • Keys and values with spaces must be quoted.