【问题标题】:Bash and Docker: strange heredoc behavior with read loopBash 和 Docker:带有读取循环的奇怪的heredoc 行为
【发布时间】:2019-02-05 12:08:22
【问题描述】:

在使用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

我在这里错过了什么?

【问题讨论】:

    标签: bash docker heredoc


    【解决方案1】:

    您的第一个“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 手册页所述:

    ...如果word不加引号,则here-document的所有行都进行参数扩展,...

    【讨论】:

    • 确实不错。另一种选择是逃离美元。
    猜你喜欢
    • 2013-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-24
    • 2012-11-27
    • 2014-10-27
    • 2011-01-30
    • 2014-05-12
    相关资源
    最近更新 更多