Dockerfile RUN命令省略字符以字符串中的“$”开头

问题描述 投票:0回答:1

我试图将以下字符串打印到文件:

"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"  
docker dockerfile alpine
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.