Search code examples
bashdotenv

How to fix export variables from .env in bash wrapped in quotes


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

Solution

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