Iterating Over Arrays Safely

Updated

October 31, 2026

Iterating Over Arrays Safely

Never iterate over unquoted arrays or use ${array[*]}. Always iterate with "${array[@]}":

files=("file with spaces.txt" "another.log")

# SAFE: Preserves whitespace boundaries
for file in "${files[@]}"; do
    echo "Processing: $file"
done

# Iterating by index (for parallel or indexed arrays):
for i in "${!files[@]}"; do
    echo "Index $i contains ${files[$i]}"
done