Score:1

Read from .env file and set as bash variables

ca flag

How can I read an .env file and set the variables as bash variables? Currently, I'm able to read it and export them as environment variables.

If the file contains the variables:

DB_NAME=mydb
DB_PASSWORD=abcd1234

Then, DB_NAME and DB_PASSWORD will be bash variables and they will contain the respective values.

Score:1
cn flag

If a text file is formatted as

DB_NAME=mydb
DB_PASSWORD=abcd1234

then these variables can be set in the current bash shell simply by sourcing the file as:

source my_custom.env
fr flag
this WON'T work for any .env variable that contains certain characters. e.g. `PASSWORD=abcd;1234` is a valid .env file but would not work in bash with `source` (it'd read just 'abcd')
vanadium avatar
cn flag
@istepaniuk There is also something like "quoting" in bash to handle characters with a special meaning.
fr flag
@vanadium That's true when the .env file is a bash/shell compatible file (such as PHP DotEnv and others). But not true for many other common .env implementations, such as docker's envfiles, where there is no expansion and quoting would result in the actual quotes being included in the value. The later case is common enough that maybe a "depends on your .env file standard" clarification could improve this answer.
vanadium avatar
cn flag
@istepaniuk A more broad answer may be suited for another Stackexchange site, but not for this site dedicated to Ubuntu
Farhan M. avatar
ca flag
That's awesome! Thanks!
Hannu avatar
ca flag
For answers to almost all your Bash qquestions, find and study the Bash guides at www.tldp.org
vanadium avatar
cn flag
Please "accept" the answer if it helped you: click the checkmark next to the question.
Score:0
mr flag

An improved approach that ignores comments is

export $(grep -v '^#' my_custom.env | xargs)
karel avatar
sa flag
It's not necessarily always an improvement to invert match and ignore comments.
in flag
A better answer would explain that grep -v does an inverse match on the regex, which matches # at start of line, ... What's xargs doing here? Handling spaces/non-ASCII??
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.