How to iterate over list which contains whitespaces in bash

Solution 1:

To loop through items properly you need to use ${var[@]}. And you need to quote it to make sure that the items with spaces are not split: "${var[@]}".

All together:

x=("some word" "other word" "third word")
for word in "${x[@]}" ; do
  echo -e "$word\n"
done

Or, saner (thanks Charles Duffy) with printf:

x=("some word" "other word" "third word")
for word in "${x[@]}" ; do
  printf '%s\n\n' "$word"
done

Solution 2:

Two possible solutions, one similar to fedorqui's solution, without the extra ',', and another using array indexing:

x=( 'some word' 'other word' 'third word')

# Use array indexing
let len=${#x[@]}-1
for i in $(seq 0 $len); do
        echo -e "${x[i]}"
done

# Use array expansion
for word in "${x[@]}" ; do
  echo -e "$word"
done

Output:

some word
other word
third word
some word
other word
third word

edit: fixed issues with the indexed solution as pointed out by cravoori