Bash 和 Docker : strange heredoc behavior with read loop

标签 bash docker heredoc

当使用 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/

相关文章:

linux - Windows 10 ubuntu linux bash sshpass获取伪终端失败

docker - Kafka无法在Linux机器中与Zookeeper连接

php - 在 PHP 中使用 heredoc 有什么好处?

bash - 使用 heredoc 重定向命令输出

java - 在 Java 中使用长字符串(heredocs)——可读的方法?

linux - 将syslog文件复制到linux中的新目录

html - sed HTML </>标签

linux - (Bash) 如何监控目录中的文件更改(创建、删除、重命名)

docker - Docker自包含的微服务

docker - .NET Core 项目的 AppSettings 未在 Docker 容器中覆盖