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?
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, ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With