23

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.

Farhan M.
  • 333

2 Answers2

34

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
vanadium
  • 98,427
  • For answers to almost all your Bash qquestions, find and study the Bash guides at www.tldp.org – Hannu Jan 29 '22 at 19:39
  • 3
    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') – istepaniuk Feb 20 '23 at 20:16
  • @istepaniuk There is also something like "quoting" in bash to handle characters with a special meaning. – vanadium Feb 23 '23 at 09:19
  • 1
    @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. – istepaniuk Feb 23 '23 at 10:30
  • @istepaniuk A more broad answer may be suited for another Stackexchange site, but not for this site dedicated to Ubuntu – vanadium Feb 24 '23 at 15:09
7

An improved approach that ignores comments is

export $(grep -v '^#' my_custom.env | xargs)
  • It's not necessarily always an improvement to invert match and ignore comments. – karel Jan 16 '23 at 00:23
  • 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?? – pbhj Jan 19 '23 at 09:29
  • This approach forks lots, grep $() and the |xargs all have processes. source is a bash builtin , i.e. its does not fork at all – teknopaul Feb 04 '24 at 20:29
  • While it doesn't cause problems with the specific example being asked, it creates problems for env files that include quoted values. It removes the quotes and breaks things – frogstarr78 Jul 20 '24 at 20:35