swdev
swdev

Reputation: 3061

How to preserve spaces in Bash "for loop" expression

I have function that print lines with spaces and need to loop through the line with a for..in loop. How do I preserve the spaces and not tokenize based on them.

function getTwoThings
{
    echo "A B C"
    echo "X Y Z"
}

for L in `getTwoThings`
do
    echo $L
done

for L in "`getTwoThings`"
do
    echo $L
done

Produces either six things or one thing.

A
B
C
X
Y
Z

A B C X Y Z

How do I get it to produce two things?

Upvotes: 1

Views: 159

Answers (1)

anubhava
anubhava

Reputation: 785196

Read it like this using process substitution:

while IFS= read -r line; do
   echo "$line"
done < <(getTwoThings)

Output:

A B C
X Y Z

Upvotes: 2

Related Questions