Bash 和 Docker:带有读取循环的奇怪的 heredoc 行为
Bash and Docker: strange heredoc behavior with read loop
我在使用 while read
循环迭代多个值时观察到一个奇怪的行为。怪癖是当我使用 heredoc 将代码传递到 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, ...
我在使用 while read
循环迭代多个值时观察到一个奇怪的行为。怪癖是当我使用 heredoc 将代码传递到 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, ...