7

Could you please tell me how to iterate over list where items can contain whitespaces?

x=("some word", "other word", "third word")
for word in $x ; do
    echo -e "$word\n"
done

how to force it to output:

some word
other word
third word

instead of:

some
word
(...)
third
word

2 Answers 2

8

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
Sign up to request clarification or add additional context in comments.

3 Comments

you may want to set -f to turn globbing off. Please see wiki.bash-hackers.org/commands/builtin/set
@cravoori: that's not necessary as long as all references to the variable(s) are in double-quotes -- which they are.
echo -e? If what the OP really wants is an extra newline on the end, printf '%s\n\n' would be saner.
3

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

1 Comment

your array indexing solution is bogus. It prints 3 array members regardless of array length. You need to put seq inside a command substitution. Also, start with 0 instead of 1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.