bash - 来自printf的Docker ENV值不起作用

标签 bash docker sed dockerfile

我的情况有点复杂:

  • 我的Dockerfile中有一个环境变量,它是一个路径:ENV ORACLE_HOME=/home/oracle
  • 我需要稍后进行一些文件操作,所以我正在使用sed
  • 不幸的是,在使用变量之前,我需要转义sed的路径字符\

  • 这就是我所拥有的:
    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/

    相关文章:

    linux - 多线修剪

    regex - 如何在特定范围的列中替换分隔为空白的管道?

    bash - Subshel​​l没有新的进程ID?

    amazon-web-services - 是否可以在同一个 AWS EC2 中运行多个 Web 实例?

    spring - 如何在docker容器中配置spring cloud oauth2

    docker - 在单个服务器上运行 Kubernetes 有意义吗?

    sed - 如何使用sed重命名fasta文件头

    linux - 如何在 Alpine Linux 中使用 bash 脚本?

    linux - 如何将变量替换为 bash 脚本,然后在 Linux 中的远程服务器上运行

    linux - 找不到相关命令