How to iterate over list which contains whitespaces in bash

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

Leave a Comment