I am trying to have my script read from a .env file and export environment variables in the session I am calling this script from.

Here's my .env file:

# Some comment here
NODE_ENV=development
JWKS_AUDIENCE=test test02

and my bash script that reads from this file:

set-local-env.sh:

IFS='=' # delimiter
while read LINE
    do 
        if [[ $LINE =~ ^\#.* ]] ;
        then
            continue
        fi
        read -ra ADDR <<< "$LINE"
        export ${ADDR[0]}=\"${ADDR[1]}\"
done < .env.development

export myvar="sup"

I run it by using source to set the environment of the session running it:

$ source ./set-local-env.sh
-bash: export: `"development "': not a valid identifier
-bash: export: `"test test02"': not a valid identifier

The last export at the bottom myvar="sup" is working:

$ echo $myvar
sup

My guess was that the command isn't being constructed properly, what I am get out of export ${ADDR[0]}=\"${ADDR[1]}\" is:

  • export NODE_ENV="development"
  • export JWKS_AUDIENCE="test test02"

I tried echoing out the export commands (i.e. echo export ${ADDR[0]}=\"${ADDR[1]}\") and here's what I got:

export NODE_ENV "development"
export JWKS_AUDIENCE "test test02"
export myvar=sup

The two exports that are generated from inside the loop do not have the equal sign. Why is that happening and how can I fix it?

2 Answers

2
oguzismail On Best Solutions

You don't need this:

read -ra ADDR <<< "$LINE"
export ${ADDR[0]}=\"${ADDR[1]}\"

and this:

IFS='='

Just do as follows and you're good to go:

export "$LINE"
0
vintnes On

Why not just source your variables normally, then export them by name alone?

. file.env
while IFS=\= read foo bar; do
  [[ ! "$foo" =~ ^\# ]] && export $foo
done < file.env