我观察到使用while read
循环迭代多个值时的奇怪行为。怪癖是,当我使用 heredoc 将代码传递到 Docker 容器中时,正在读取的变量总是空的:
$ docker run --rm -i ubuntu:18.04 << EOF
echo -e "123n456"|while read f; do echo "Value: $f"; done
EOF
Value:
Value:
使用 heredoc 变量重写的相同内容按预期工作:
$ docker run --rm -i ubuntu:18.04 <<< 'echo -e "123n456"|while read f; do echo "Value: $f"; done'
Value: 123
Value: 456
而且如果我以交互方式运行它:
$ docker run --rm -it ubuntu:18.04 bash
root@0d71388ad90d:/# echo -e "123n456"|while read f; do echo "Value: $f"; done
Value: 123
Value: 456
我在这里错过了什么?
您的第一个"here doc"执行参数扩展,$f
变为空字符串。为避免它,引用EOF
:
docker run --rm -i ubuntu:18.04 <<'EOF'
echo -e "123n456"|while read f; do echo "Value: $f"; done
EOF
正如 bash 手册页中所述:
。如果单词没有引号,则此处文档的所有行都受到参数扩展的影响,...