skip to Main Content

How to run sed command and save the result to one new Variable in docker.
The sed will replace the last occurrence of ‘.’ and replace with ‘_’

Example :

JOB_NAME_WITH_VERSION = test_git_0.1 and wanted result is ZIP_FILE_NAME = test_git_0_1

--Dockerfile
    
RUN ZIP_FILE_NAME=$(echo ${JOB_NAME_WITH_VERSION} | sed 's/(.*)./1_/') && export ZIP_FILE_NAME 
        
RUN echo "Zip file Name found : $ZIP_FILE_NAME"

I tried this in my docker file but the result is empty

Zip file Name found :

2

Answers


  1. The issue here is that every RUN command results in a new layer, so whatever shell variable was declared in previous layers is subsequently lost.

    Compare this:

    FROM ubuntu
    RUN JOB="FOOBAR"
    RUN echo "${JOB}"
    
    $ docker build .
    ...
    Step 3/3 : RUN echo "${JOB}"
     ---> Running in c4b7d1632c7e
    
    ...
    

    to this:

    FROM ubuntu
    RUN JOB="FOOBAR" && echo "${JOB}"
    
    $ docker build .
    ...
    Step 2/2 : RUN JOB="FOOBAR" && echo "${JOB}"
     ---> Running in c11049d1687f
    FOOBAR
    ...
    

    so as a workaround, if using a single RUN command is not an option for whatever reason, write the variable to disk and read it when needed, e.g.:

    FROM ubuntu
    RUN JOB="FOOBAR" && echo "${JOB}" > /tmp/job_var
    RUN cat /tmp/job_var
    
    $ docker build .
    ...
    Step 3/3 : RUN cat /tmp/job_var
     ---> Running in a346c30c2cd5
    FOOBAR
    ...
    
    Login or Signup to reply.
  2. Each RUN statement in a Dockerfile is run in a separate shell. So once a statement is done, all environment variables are lost. Even if they are exported.

    To do what you want to do, you can combine your RUN statements like this

    RUN ZIP_FILE_NAME=$(echo ${JOB_NAME_WITH_VERSION} | sed 's/(.*)./1_/') && 
        export ZIP_FILE_NAME && 
        echo "Zip file Name found : $ZIP_FILE_NAME"
    

    As your variable is lost once the RUN statement is finished, your environment variable won’t be available in your container when it runs. To have an environment variable available there, you need to use the ENV statement.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search