Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell how to set environment variables from .env file

Tags:

shell

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?

like image 882
James Lin Avatar asked Apr 06 '17 23:04

James Lin


People also ask

How do I set an environment variable in shell?

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.

Can I use variables in .env file?

The . env file lets you customize your individual working environment variables.

How do I import a .env variable?

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.


2 Answers

If your lines are valid, trusted shell but for the export command

This 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 

If your lines are not valid shell

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 
like image 163
Charles Duffy Avatar answered Sep 19 '22 04:09

Charles Duffy


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.

like image 21
voutasaurus Avatar answered Sep 18 '22 04:09

voutasaurus