【问题标题】:Dockerfile RUN command omits characters starts with "$" from a stringDockerfile RUN 命令从字符串中省略以“$”开头的字符
【发布时间】:2019-02-25 16:41:02
【问题描述】:

我正在尝试将以下字符串打印到文件中:

"hellow world $xHbbbbbbbb"  

我有两种选择:

printf "hellow world \$xHbbbbbbbb\n" > /myfile1  
echo "hellow world \$xHbbbbbbbb\n" > /myfile2  

它在终端上运行良好。
当我像这样使用 Dockerfile 构建它时:

cat > Deleteme <<EOF
FROM alpine:latest
RUN printf "hellow world \$xHbbbbbbbb\n" > /myfile1
RUN echo "hellow world \$xHbbbbbbbb\n" > /myfile2
EOF

docker build -t deleteme -f Deleteme .  
docker run --rm -it deleteme sh -c "cat /myfile1 && cat /myfile2"  

输出是:

hellow world 
hellow world \n

为什么RUN 命令省略了$xHbbbbbbbb
我想这是因为 $ 将其标识为变量,但它在终端上对我有用,所以我不明白为什么它在 Dockerfile 上也不起作用。
如何将以下字符串写入文件:

"hellow world $xHbbbbbbbb"  

【问题讨论】:

  • 使用双反斜杠\\$xHbbbbbbbb
  • @ponury-kostek 它不起作用:Step 1/2 : FROM alpine:latest ---&gt; caf27325b298 Step 2/2 : RUN echo "hellow world \\n" &gt; /myfile2 ---&gt; Running in 04e688ab920a ---&gt; 381811b5961e Removing intermediate container 04e688ab920a Successfully built 381811b5961e
  • 你不应该使用cat &gt; Deleteme &lt;&lt;'EOF' 吗?

标签: docker dockerfile alpine


【解决方案1】:

在 Dockerfile 中,$xHbbbbbbbb 确实评估为环境变量
(有关用法和示例,请参阅Docker Documentation | Environment replacement)。

要获得预期的结果,您需要同时转义 \$
此外,在 echo 中,\n 不会被解释为换行符,除非指定了 -e 选项,但看起来您可以省略它(请参阅 echo man page 了解更多信息)。

把它放在一起:

cat > Deleteme <<EOF
FROM alpine:latest
RUN printf "hellow world \\\$xHbbbbbbbb\n" > /myfile1
RUN echo "hellow world \\\$xHbbbbbbbb" > /myfile2
EOF

具有以下Deleteme 文件的结果:

FROM alpine:latest
RUN printf "hellow world \$xHbbbbbbbb\n" > /myfile1
RUN echo "hellow world \$xHbbbbbbbb" > /myfile2

docker 输出:

hellow world $xHbbbbbbbb
hellow world $xHbbbbbbbb

【讨论】:

    猜你喜欢
    • 2018-10-18
    • 2010-10-11
    • 2015-06-19
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 2014-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多