Home > OS >  How to set an environment variable from .env file that references other environment variables
How to set an environment variable from .env file that references other environment variables

Time:07-21

I have a file called .env with environment variables:

MY_VAR="a value"
A_VAR=3
ANOTHER_VAR=${PWD}

I use this file to set the variables for a node.js script before its execution like this:

env $(cat .env | xargs) node script.js

This works fine as long as the values in the .env file are static, in this example here though I would like ${PWD} for ANOTHER_VAR to expand into the current working directory (which is available in the PWD environment variable, I have checked that).

If I try it with

env -vS "ANOTHER_VAR=${PWD}" printenv ANOTHER_VAR

it works fine, but somehow when I load the variables from the file with cat & xargs the ${PWD} doesn't get expanded.

So when I try this

env $(cat .env | xargs) printenv ANOTHER_VAR

it returns ${PWD} instead of (for example) /Users/myuser/some/folder.

I have tried everything I can imagine and googled around but I just cannot get env to actually interpret the {$PWD}, how can I load environment variables from a .env file such that the values can reference other environment variables?

I am on OS X 12.4 and my shell is zsh 5.8.1 (x86_64-apple-darwin21.0)

CodePudding user response:

The problem is that parameter expansion happens before command substitution. That is why a line in .env which contains references to other environment-variables is not expanded.

A work-around would be to ditch the use of env and use a simple shell-syntax using source.

bash -c 'source ".env"; printenv ANOTHER_VAR'

CodePudding user response:

Finally got it working thanks to the hint from @kvantour, this does the trick for me:

bash -c 'set -a; source .env; printenv ANOTHER_VAR'

The env variable is only available for the printenv command.

  • Related