当使用 while read 循环迭代多个值时,我观察到奇怪的行为。奇怪的是,当我使用定界文档将代码传递到 Docker 容器时,读取的变量始终为空:
$ docker run --rm -i ubuntu:18.04 << EOF
echo -e "123\n456"|while read f; do echo "Value: $f"; done
EOF
Value:
Value:
使用heredoc变量重写的内容按预期工作:
$ docker run --rm -i ubuntu:18.04 <<< 'echo -e "123\n456"|while read f; do echo "Value: $f"; done'
Value: 123
Value: 456
如果我以交互方式运行它:
$ 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
我在这里缺少什么?
最佳答案
您的第一个“here doc”执行参数扩展,并且 $f
变为空字符串。为了避免它引用EOF
:
docker run --rm -i ubuntu:18.04 <<'EOF'
echo -e "123\n456"|while read f; do echo "Value: $f"; done
EOF
正如 bash 手册页中所述:
... If word is unquoted, all lines of the here-document are subjected to parameter expansion, ...
关于Bash 和 Docker : strange heredoc behavior with read loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52098842/