Arrays
A Bash array holds a list of values under one name, indexed from zero, and it comes with its own small family of special expansions worth knowing by heart.
Creating and reading an array
bash fruits.sh
#!/bin/bash fruits=("apple" "banana" "cherry") echo "${fruits[0]}" echo "${fruits[2]}" echo "Total: ${#fruits[@]}"
Terminal output
apple cherry Total: 3
${fruits[0]} reads a single element (indexing starts at 0), and ${#fruits[@]} gives the number of elements — the curly braces around every array expansion aren't optional.
Looping over an array
bash loop-fruits.sh
#!/bin/bash fruits=("apple" "banana" "cherry") for fruit in "${fruits[@]}"; do echo "- $fruit" done
Terminal output
- apple - banana - cherry
Adding elements
bash append.sh
#!/bin/bash fruits=("apple" "banana") fruits+=("cherry") echo "${fruits[@]}"
Terminal output
apple banana cherry
@ vs *, again: just like
"$@" with script arguments, "${fruits[@]}" (quoted) expands each element as its own separate word — safe even if an element contains spaces — while "${fruits[*]}" joins everything into one string. Use "${arr[@]}" when looping.