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
- Indexed array:
fruits=("apple" "banana" "cherry")
echo "${fruits[0]}"
- Iterate:
for f in "${fruits[@]}"; do echo "$f"; done
- 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 -Afor associative arrays causes unexpected behavior. - Keys and values with spaces must be quoted.