0

I am having trouble using a Here Document variable in a loop. Because this works

while IFS= read -r line; do
  echo "(${line})"
done <<EOF
one
two
three
EOF

But this doesn't

foo=<<EOF
one
two
three
EOF

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

Now I am a bit of a noob in bash scripting. Besides having question marks above my head I wonder how I can preserve the second syntax (the here document at the top of my script) and still make it work somehow.

Thanks for your help.

2 Answers 2

7

This doesn't set the variable foo to the contents of the heredoc:

foo=<<EOF
one
two
three
EOF

It's a variable assignment to an empty string, with a redirection. This might make it clearer what's happening:

foo=""  <<EOF
one
two
three
EOF

But you don't really need heredocs for this. Just do:

foo="one
two
three"
2

Apparently, you want to have an inline document variable and then split it on lines. You could do it like this:

lines=$(cat <<EOF
one two
three
four
EOF
)

IFS=$'\n'     # split on non-empty lines
set -o noglob # disable globbing as we only want the split part.

# use split+glob (leave ${lines} unquoted):
for line in ${lines}; do
   echo "${line}"
done

Note how I set the IFS to not split on line. The default would split on spc/tab/newline delimited words.

4
  • That's what I am using right now, thanks for sharing
    – vdegenne
    Jan 29, 2020 at 12:23
  • Happy to help. I notice there is no accepted answer yet. I did like the point @muru made regarding the empty assignment. Anyway, marking answers help contributors pick questions lacking answers, Feb 3, 2020 at 10:13
  • 1
    I am well aware of that, I just like to wait few days before validating an answer because as you said new contributors can notice the lack of answers and add their own contribution, it's always good to have few different views/opinions on one matter, it's not that I just asked and left ;)
    – vdegenne
    Feb 6, 2020 at 6:34
  • Late but I hope you'll accept this answer, it sure helped me! Jul 2, 2021 at 14:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .