skip to Main Content

This is my
.env.test

S3_READY_MESSAGE="s3 is ready"
NGINX_READY_MESSAGE="nginx is ready"

Bash to output variables

$ echo $(cat ../../../.env.test | grep -o -E '^[^#]+')

output:

S3_READY_MESSAGE="s3 is ready" NGINX_READY_MESSAGE="nginx is ready"

Bash to export variables

export $(cat ../../../.env.test | grep -o -E '^[^#]+')

error

bash: export: `ready"': not a valid identifier
bash: export: `ready"': not a valid identifier

2

Answers


  1. Chosen as BEST ANSWER

    I originally had a solution which exported fine but it doesn't work with quoted content that has spaces.

    solution 1 - CON: only works with no spaces in value

    .env

    var=somethingwasok
    var="something with spaces was not ok"
    
    export $(cat ./.env | grep -o -E '^[^#]+' | xargs)
    

    solution 2 CON: Uses eval, so may be deemed unsafe.

    (As long as I am doing this manually then I know the file I'm exporting so don't mind using eval in this case.)

    #  output .env   | replace each valid line with export | remove comments
    #  || export all          ||    val=something               ||
    #  /                     /    export val=something        /
    eval $(cat ./.env | sed -E 's/^(w)/export 1/g'         | grep -o -E '^[^#]+')
    

  2. For this particular sample input you can make use of bash's set -a/+a in conjunction with sourcing .env.test:

    $ set -a                                 # enable  auto-export of variable assignments
    $ source ../../../.env.test              # alternatively replace 'source' with '.'
    $ set +a                                 # disable auto-export of variable assignments
    

    Results:

    $ typeset -p S3_READY_MESSAGE NGINX_READY_MESSAGE
    declare -x S3_READY_MESSAGE="s3 is ready"
    declare -x NGINX_READY_MESSAGE="nginx is ready"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search