skip to Main Content

I have an application that runs inside a docker container. First I build the image and then run the container. My run command is:

docker run --rm -it -e MODE=custom -e Station=RT -e StartDateReport=2022-09-10 -e Period=1 my-image:1.0.0

I declare the variables MODE, Station, StartDateReport and Period as environment variables. When I start a terminal from the container and type echo $MODE I will get the correct value, custom.

So far, so good, but I am interested in using these variables in a bash script. For example in start.sh I have the following code:

#!/bin/bash

if [[ $MODE == custom ]]; then
   // do sth
fi

and here inside the script my variable MODE is undefined, and hence I obtain wrong results.

EDIT

As discussed in the comments below, my application if based on a cronjob to start running.

I managed to solve by myself the problem and the answer is in the comments.

2

Answers


  1. Chosen as BEST ANSWER

    I found the solution for this problem, so I will post the answer here to help others that have the same problem. I found the solution here: How to load Docker environment variables in container

    I included export xargs --null --max-args=1 echo < /proc/1/environ in start.sh

    Thus, start.sh will be:

    #!/bin/bash
    
    export xargs --null --max-args=1 echo < /proc/1/environ
    
    if [[ $MODE == custom ]]; then
       // do sth
    fi
    

  2. In your environment, does your variable definition have the form

    export MODE="custom"
    

    Modified version of your script:

    #!/bin/bash
    
    test -z "${MODE}" && ( echo -e "nt  MODE was not exported from calling environment.n" ; exit 1 )
    
    if [[ $MODE == custom ]]
    then
        #// do sth
        echo "do sth"
    fi
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search