Let's say I have .env file contains lines like below:
USERNAME=ABC PASSWORD=PASS
Unlike the normal ones have export
prefix so I cannot source the file directly.
What's the easiest way to create a shell script that loads content from .env file and set them as environment variables?
You can set your own variables at the command line per session, or make them permanent by placing them into the ~/. bashrc file, ~/. profile , or whichever startup file you use for your default shell. On the command line, enter your environment variable and its value as you did earlier when changing the PATH variable.
The . env file lets you customize your individual working environment variables.
On the Projects page, select the project that you want to import environment variables to, and click Properties to open the Project Properties window. On the General page, click Environment. In the Environment Variables dialog, click Import from File.
export
commandThis requires appropriate shell quoting. It's thus appropriate if you would have a line like foo='bar baz'
, but not if that same line would be written foo=bar baz
set -a # automatically export all variables source .env set +a
The below reads key/value pairs, and does not expect or honor shell quoting.
while IFS== read -r key value; do printf -v "$key" %s "$value" && export "$key" done
This will export everything in .env:
export $(xargs <.env)
Edit: this requires the environment values to not have whitespace. If this does not match your use case you can use the solution provided by Charles
Edit2: I recommend adding a function to your profile for this in any case so that you don't have to remember the details of set -a
or how xargs
works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With