我试图将以下字符串打印到文件:
"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"
在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