Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash and Docker: strange heredoc behavior with read loop

I'm observing a weird behaviour when using a while read loop to iterate over multiple values. The quirk is that the variable being read is always empty when I'm using a heredoc to pass the code into a Docker container:

$ docker run --rm -i ubuntu:18.04 << EOF
echo -e "123\n456"|while read f; do echo "Value: $f"; done
EOF

Value: 
Value: 

The same rewritten with a heredoc variable works as expected:

$ docker run --rm -i ubuntu:18.04 <<< 'echo -e "123\n456"|while read f; do echo "Value: $f"; done'
Value: 123
Value: 456

And also if I run it interactively:

$ docker run --rm -it ubuntu:18.04 bash
root@0d71388ad90d:/# echo -e "123\n456"|while read f; do echo "Value: $f"; done
Value: 123
Value: 456

What am I missing here?

like image 794
yktoo Avatar asked Aug 26 '26 09:08

yktoo


1 Answers

Your first "here doc" performs parameter expansion, and the $f becomes a null string. To avoid it quote the EOF:

docker run --rm -i ubuntu:18.04 <<'EOF'
echo -e "123\n456"|while read f; do echo "Value: $f"; done
EOF

As said in the bash man page:

... If word is unquoted, all lines of the here-document are subjected to parameter expansion, ...

like image 95
oliv Avatar answered Aug 29 '26 15:08

oliv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!