1

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?

1
  • 1
    Bash FAQ 001 Commented Feb 1, 2016 at 22:12

1 Answer 1

2

Read it like this using process substitution:

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

Output:

A B C
X Y Z
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, prefect answer.

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.