Home > OS >  Environment Variables inside the container, but not used in the bash script
Environment Variables inside the container, but not used in the bash script

Time:11-28

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.

CodePudding user response:

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 "\n\t  MODE was not exported from calling environment.\n" ; exit 1 )

if [[ $MODE == custom ]]
then
    #// do sth
    echo "do sth"
fi

CodePudding user response:

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
  • Related