我的情况有点复杂:
Dockerfile
中有一个环境变量,它是一个路径:ENV ORACLE_HOME=/home/oracle
\
。 这就是我所拥有的:
ENV ORACLE_HOME=/home/oracle
ENV ORACLE_HOME_ESCAPED="$(printf '%q\n' "$ORACLE_HOME")"
RUN sed 's/.*pattern.*/\"-Dsomekey='${ORACLE_HOME_ESCAPED}'\"/' file
如果RUN
仅包含简单字符,则ORACLE_HOME
行可以正常工作。我使用
printf
进行转义的命令在bash
中可以正常工作,但是在Dockerfie
中却不能工作。不幸的是,我只有
GNU bash, version 4.2.46(2)-release (x86_64-redhat-linux-gnu)
,bash 4.4没有更新,因此我无法使用${@Q}
表示法。我使用oraclelinux:7-slim
作为基本图像。关于
printf
有什么问题的任何建议吗?
最佳答案
Any suggestion about what is wrong with the printf?
printf没什么问题,但是如何使用变量存在问题。
没有
ENV
不会运行会扩展$(...)
的 shell -ENV是简单的a=b
分配,没有扩展。请尝试以下操作,并注意在扩展变量而不分配变量时如何使用引号:
FROM alpine
ENV ORACLE_HOME="not simple characters?!@#^**^&()"
RUN set -x && \
printf "%s\n" a pattern b > file && \
# https://stackoverflow.com/questions/407523/escape-a-string-for-a-sed-replace-pattern
ORACLE_HOME_ESCAPED_FOR_SED=$(printf '%s\n' "$ORACLE_HOME" | sed -e 's/[\/&]/\\&/g') && \
sed 's/.*pattern.*/"-Dsomekey='"$ORACLE_HOME_ESCAPED_FOR_SED"'"/' file
# these quotes ^ ^
# prevent word splitting
结果是:$ docker build .
...
Step 3/3 : RUN set -x && printf "%s\n" a pattern b > file && ORACLE_HOME_ESCAPED_FOR_SED=$(printf '%s\n' "$ORACLE_HOME" | sed -e 's/[\/&]/\\&/g') && sed 's/.*pattern.*/"-Dsomekey='"$ORACLE_HOME_ESCAPED_FOR_SED"'"/' file
---> Running in 9a98e726e145
+ printf '%s\n' a pattern b
+ printf '%s\n' 'not simple characters?!@#^**^&()'
+ sed -e 's/[\/&]/\\&/g'
+ ORACLE_HOME_ESCAPED_FOR_SED='not simple characters?!@#^**^\&()'
+ sed 's/.*pattern.*/"-Dsomekey=not simple characters?!@#^**^\&()"/' file
a
"-Dsomekey=not simple characters?!@#^**^&()"
b
Removing intermediate container 9a98e726e145
---> 9f9276112bf0
Successfully built 9f9276112bf0
I need to do some file manipulation later, so I am using sed
取决于要执行的操作-在模板情况下,
envsubst
就足够了。I need to escape the path characters \ for sed before I use the variable.
是的,您可以这样做-或者使用其他
s
分隔符-s!something!somethingelse!
。
关于bash - 来自printf的Docker ENV值不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64284828/