Indexed arrays hold ordered lists; associative arrays (Bash 4+) map keys to values. Arrays are Bash-specific—avoid them when you need pure POSIX sh.
Indexed arrays
fruits=("apple" "banana" "cherry")
echo "first: ${fruits[0]}"
echo "all: ${fruits[@]}"
echo "count: ${#fruits[@]}"${#arr[@]} is length; indices start at 0.
Append and iterate
nums=()
nums+=(1)
nums+=(2 3)
for n in "${nums[@]}"; do
echo "n=$n"
doneAlways quote "${arr[@]}" to preserve separate elements.
Associative arrays
declare -A capitals
capitals[UK]="London"
capitals[FR]="Paris"
echo "${capitals[UK]}"Requires Bash 4+—check bash --version on macOS if features fail.
Important interview questions and answers
- Q: 0-based arrays?
A: Yes in Bash indexed arrays—unlike R's 1-based vectors. - Q: declare -A?
A: Creates an associative (hash) array.
Self-check
- How do you get array length?
- Why quote ${arr[@]} in loops?
Tip: macOS default Bash 3.2 lacks associative arrays—check version before declare -A.
Interview prep
- Indexed array access?
${arr[0]} first element.
- declare -A?
Associative array (Bash 4+).