1199

TL;DR: How do I export a set of key/value pairs from a text file into the shell environment?


For the record, below is the original version of the question, with examples.

I'm writing a script in bash which parses files with 3 variables in a certain folder, this is one of them:

MINIENTREGA_FECHALIMITE="2011-03-31"
MINIENTREGA_FICHEROS="informe.txt programa.c"
MINIENTREGA_DESTINO="./destino/entrega-prac1"

This file is stored in ./conf/prac1

My script minientrega.sh then parses the file using this code:

cat ./conf/$1 | while read line; do
    export $line
done

But when I execute minientrega.sh prac1 in the command line it doesn't set the environment variables

I also tried using source ./conf/$1 but the same problem still applies

Maybe there is some other way to do this, I just need to use the environment variables of the file I pass as the argument of my script.

7
  • Same on unix: unix.stackexchange.com/questions/31797/… Commented Nov 19, 2014 at 14:13
  • 6
    This is a great question but is phrased way too specifically, with particular variable names ("MINIENTREGA_FECHALIMITE"? what does that mean?) and numbers (3). The general question is simply, "How do I export a set of key/value pairs from a text file into the shell environment". Commented Nov 14, 2018 at 5:05
  • 3
    Also, this has already been answered on unix.SE and is arguably more on-topic there. Commented Dec 25, 2018 at 3:12
  • 5
    I have my reservation on marking this question as dupe of a question that appeared 4 years later.
    – anubhava
    Commented Sep 24, 2022 at 16:18
  • 1
    @anubhava, that's fair, but the answer quality is pretty atrocious here. The first and foremost goal above all others is to give people good information, no? (There are some good answers on this question, but they're low-scoring compared to the bug-filled one at the top; this is a place where Stack Overflow's format and rules are not serving our community/readers well). Commented Apr 13, 2023 at 11:48

50 Answers 50

1680

This might be helpful:

export $(cat .env | xargs) && rails c

Reason why I use this is if I want to test .env stuff in my rails console.

gabrielf came up with a good way to keep the variables local. This solves the potential problem when going from project to project.

env $(cat .env | xargs) rails

I've tested this with bash 3.2.51(1)-release


Update:

To ignore lines that start with #, use this (thanks to Pete's comment):

export $(grep -v '^#' .env | xargs)

And if you want to unset all of the variables defined in the file, use this:

unset $(grep -v '^#' .env | sed -E 's/(.*)=.*/\1/' | xargs)

Update:

To also handle values with spaces, use:

export $(grep -v '^#' .env | xargs -d '\n')

on GNU systems -- or:

export $(grep -v '^#' .env | xargs -0)

on BSD systems.


From this answer you can auto-detect the OS with this:

export-env.sh

#!/bin/sh

## Usage:
##   . ./export-env.sh ; $COMMAND
##   . ./export-env.sh ; echo ${MINIENTREGA_FECHALIMITE}

unamestr=$(uname)
if [ "$unamestr" = 'Linux' ]; then

  export $(grep -v '^#' .env | xargs -d '\n')

elif [ "$unamestr" = 'FreeBSD' ] || [ "$unamestr" = 'Darwin' ]; then

  export $(grep -v '^#' .env | xargs -0)

fi

10
  • 55
    Here's a shorter variation eval $(cat .env) rails
    – manalang
    Commented Apr 26, 2016 at 15:57
  • 1
    on my end this doesn't seem to work with multiple entries in the .env file because it doesn't preseve newlines, so you get a SOME_ENV_VAR=sdfajkasldfjlasdkfj ANOTHERVAR=sdafjasdjasdfkl all as a single var (because it's all after a single line export).
    – Kzqai
    Commented Dec 15, 2022 at 17:01
  • 3
    This is too much complicated - pls consider simpler way with set -o allexport below
    – Nam G VU
    Commented Jan 5, 2023 at 16:54
  • In my cases a \r was added which caused wrong values. I added tr -d '\r' but tr '\r' '\0' will also work. Final command is export $(grep -v '^#' .env | tr '\r' '\0' | xargs -d '\n') Commented Mar 1, 2023 at 19:07
  • 3
    No, export $(grep -v '^#' .env | xargs -0) is not correct on GNU systems. The unquoted expansion still word-splits on spaces; the fact that xargs is emitting NULs doesn't change that. (And some versions of bash just silently delete NULs from command substitution results, so the exact behavior that code has is version-dependent and thus not reliably testable). And for that matter, xargs -d '\n' is unnecessary everywhere, because the newline character is present in IFS, so in command substitution results it's parsed exactly the same way as a space. Commented Apr 13, 2023 at 11:52
1063

-o allexport enables all following variable definitions to be exported. +o allexport disables this feature.

set -o allexport
source conf-file
set +o allexport
6
  • 33
    or the one-liner set -o allexport && source conf-file && set +o allexport. Thanks for the great share @user4040650.
    – 2upmedia
    Commented Dec 12, 2022 at 22:49
  • 6
    This works in a script Commented Dec 30, 2022 at 2:12
  • 1
    This works. Can confirm even with $ special characters.
    – JP Zhang
    Commented Nov 13, 2023 at 15:19
  • great! but worth to mention: source seems to be a bash-only-command Commented Apr 24 at 8:46
  • Could someone explain the absolute upside-down counterintuitiveness of the meaning of +o and -o? Looks like their meaning is the opposite of what any sane person might guess. Commented May 29 at 12:51
384

Problem with your approach is the export in the while loop is happening in a sub shell, and those variable will not be available in current shell (parent shell of while loop).

Add export command in the file itself:

export MINIENTREGA_FECHALIMITE="2011-03-31"
export MINIENTREGA_FICHEROS="informe.txt programa.c"
export MINIENTREGA_DESTINO="./destino/entrega-prac1"

Then you need to source in the file in current shell using:

. ./conf/prac1

OR

source ./conf/prac1
8
  • 6
    And if it's not from a file, use < <(commands that generate output)
    – o11c
    Commented Aug 31, 2017 at 0:10
  • 15
    You have a more clean solution, I have a preference for set -o allexport
    – heralight
    Commented Oct 28, 2018 at 9:51
  • 7
    If using this .env file between systems, inserting export would break it for things like Java, SystemD, or other tools
    – FilBot3
    Commented Feb 15, 2019 at 17:52
  • 2
    awk '{print "export " $0}' envfile convenience command to prepend export to the beginning of every line
    – Shardj
    Commented Mar 31, 2020 at 10:46
  • 3
    You don't need to prefix with export if you use . ./conf/prac1
    – Stokedout
    Commented Apr 7, 2021 at 8:42
351
set -a
. ./env.txt
set +a

If env.txt is like:

VAR1=1
VAR2=2
VAR3=3
...

Explanations -a is equivalent to allexport. In other words, every variable assignment in the shell is exported into the environment (to be used by multiple child processes). More information can be found in the Set builtin documentation:

-a     Each variable or function that is created or modified is given the export attribute and marked for export to the environment of subsequent commands.

Using ‘+’ rather than ‘-’ causes these options to be turned off. The options can also be used upon invocation of the shell. The current set of options may be found in $-.

Tradeoffs. This recipe secures variable information in the script from being logged on the command line. This may be desired if the script contains sensitive information, however it could also be a hassle when debugging. With sensitive information like encryption keys, a plaintext file may not be an appropriate place for that especially if you're version controlling the file.

3
  • 1
    what if there is a comment? and VAR2=$VAR1?
    – None
    Commented Jan 22, 2022 at 11:45
  • 3
    Hi @Alexis. The . command used here is essentially like typing on the terminal. You can try it yourself on the terminal and see what the results would be. Comments will be ignored and references to other variables will work so long as they have been defined earlier. Commented Jan 25, 2022 at 3:35
  • 1
    Yes, I tried it was working that way. Thanks for the follow-up!
    – None
    Commented Jan 25, 2022 at 3:50
125

I found the most efficient way is:

export $(xargs < .env)

Explanation

When we have a .env file like this:

key=val
foo=bar

run xargs < .env will get key=val foo=bar

so we will get an export key=val foo=bar and it's exactly what we need!

Limitation

  1. It doesn't handle cases where the values have spaces in them. Commands such as env produce this format. – @Shardj
0
52

The allexport option is mentioned in a couple of other answers here, for which set -a is the shortcut. Sourcing the .env really is better than looping over lines and exporting because it allows for comments, blank lines, and even environment variables generated by commands. My .bashrc includes the following:

# .env loading in the shell
dotenv () {
  set -a
  [ -f .env ] && . .env
  set +a
}

# Run dotenv on login
dotenv

# Run dotenv on every new directory
cd () {
  builtin cd $@
  dotenv
}
2
  • 5
    This looks nice, but you do you unload environment variables when you leave the directory? Commented Aug 1, 2017 at 7:37
  • 1
    I don't unset variables, and it's never been a problem. My apps tend to use variable names that are distinct, and if there is overlap, I'll set them to blank in that .env with VAR=.
    – gsf
    Commented Aug 2, 2017 at 14:41
47

The problem with source is that it requires the file to have a proper bash syntax, and some special characters will ruin it: =, ", ', <, >, and others. So in some cases you can just

source development.env

and it will work.

This version, however, withstands every special character in values:

set -a
source <(cat development.env | \
    sed -e '/^#/d;/^\s*$/d' -e "s/'/'\\\''/g" -e "s/=\(.*\)/='\1'/g")
set +a

Explanation:

  • -a means that every bash variable would become an environment variable
  • /^#/d removes comments (strings that start with #)
  • /^\s*$/d removes empty strings, including whitespace
  • "s/'/'\\\''/g" replaces every single quote with '\'', which is a trick sequence in bash to produce a quote :)
  • "s/=\(.*\)/='\1'/g" converts every a=b into a='b'

As a result, you are able to use special characters :)

To debug this code, replace source with cat and you'll see what this command produces.


Note for direnv users: it has a helper function dotenv, use it instead in your .envrc file:

[ -f ".env" ] && dotenv ".env"
5
  • 1
    Works for me (TM) on bash, using the following annoying string: FOO=~`#$&*()\|[=]{}; '"<>/?! Commented Feb 19, 2021 at 13:55
  • 1
    This almost worked for me, but had to swap out \s with [[:space:]] to make it also work on bash on FreeBSD/Mac: ``` source <(cat .env | sed -e '/^#/d;/^[[:space:]]*$/d' -e "s/'/'\\\''/g" -e "s/=(.*)/='\1'/g") ```
    – takilara
    Commented May 12, 2022 at 12:42
  • 2
    Worked for me, although I had to replace the last sed with: sed -e '/^#/d;/^\s*$/d' -e "s/'/'\\\''/g" -e "s/\ *=\ */=/g") to escape any spaces around the equal signs
    – Lars Ejaas
    Commented Oct 18, 2022 at 21:39
  • 1
    Perfect little nugget to add to your dotfiles - worked a treat when my .env had semicolons in it! 🙏🏼
    – cody.codes
    Commented Jul 21, 2023 at 20:15
  • 1
    Underrated answer. Env files are not always properly quoted/escaped and not meant to be run. Quoting makes them runnable in shell
    – hamilyon
    Commented Jul 24 at 10:51
34
eval $(cat .env | sed 's/^/export /')
5
  • 1
    Using eval $(cat .env | sed 's/^[^$]/export /') allows you to have empty lines for better readability.
    – Mario Uher
    Commented Jul 25, 2015 at 11:09
  • 2
    I find that cat .env | sed 's/^[^$]/export /' strips off the initial character. I.e. for a file A=foo\nB=bar\n I get export =foo\nexport =bar\n. This works better for skipping blank lines: cat .env | sed '/^$/! s/^/export /'.
    – Owen S.
    Commented Mar 2, 2017 at 18:26
  • (I also note for the sake of UNIX code golfers that you don't need cat in either case: eval $(sed 's/^/export /' .env) works just as well.)
    – Owen S.
    Commented Mar 2, 2017 at 18:28
  • dont'support commented row initial with #
    – stefcud
    Commented Jan 4, 2022 at 19:07
  • eval sed 's/^/export /' .env Commented Mar 29, 2022 at 18:07
28

Here is another sed solution, which does not run eval or require ruby:

source <(sed -E -n 's/[^#]+/export &/ p' ~/.env)

This adds export, keeping comments on lines starting with a comment.

.env contents

A=1
#B=2

sample run

$ sed -E -n 's/[^#]+/export &/ p' ~/.env
export A=1
#export B=2

I found this especially useful when constructing such a file for loading in a systemd unit file, with EnvironmentFile.

0
23

Not exactly sure why, or what I missed, but after running trough most of the answers and failing. I realized that with this .env file:

MY_VAR="hello there!"
MY_OTHER_VAR=123

I could simply do this:

source .env
echo $MY_VAR

Outputs: Hello there!

Seems to work just fine in Ubuntu linux.

4
  • If you use such and env file with Docker, your MY_VAR will contain quotes as part of the value :) docs.docker.com/compose/env-file
    – kolypto
    Commented Feb 9, 2021 at 10:01
  • 1
    @kolypto The same would happen with any other command of the higher voted answers. It is just the choice of the example. This is just to show that you can also just source it - is the core idea. The rest of the tricks is for example to cover special signs as well. Commented Jan 19, 2022 at 9:23
  • Works on mac as well. Commented Jan 12, 2023 at 3:54
  • 4
    What you're missing is that this does not define any environment variables. It defines parameters. They're completely different: no command you invoke will see these values because parameters are not inherited. Commented Mar 8, 2023 at 8:48
22

The shortest way I found:

Your .env file:

VARIABLE_NAME="A_VALUE"

Then just

. ./.env && echo ${VARIABLE_NAME}

Bonus: Because it's a short one-liner, it's very useful in package.json file

  "scripts": {
    "echo:variable": ". ./.env && echo ${VARIABLE_NAME}"
  }

Note: This way does not export the variables to the child process, check other answers if this is your need.

6
  • How about if you have a lot of variables?
    – Matteo
    Commented Aug 21, 2019 at 0:47
  • @Madeo you can add as many lines as you want, the same way as the line VARIABLE_NAME="A_VALUE" Commented Aug 26, 2019 at 7:04
  • Warning: this exports these variables into your active shell...
    – colllin
    Commented Jan 27, 2021 at 19:58
  • 4
    yes, . is a synonym for source and therefore does the same Commented Jan 28, 2021 at 7:27
  • This does not define environment variables, which is what this question is about. Commented Mar 8, 2023 at 8:45
21

I have upvoted user4040650's answer because it's both simple, and it allows comments in the file (i.e. lines starting with #), which is highly desirable for me, as comments explaining the variables can be added. Just rewriting in the context of the original question.

If the script is callled as indicated: minientrega.sh prac1, then minientrega.sh could have:

set -a # export all variables created next
source $1
set +a # stop exporting

# test that it works
echo "Ficheros: $MINIENTREGA_FICHEROS"

The following was extracted from the set documentation:

This builtin is so complicated that it deserves its own section. set allows you to change the values of shell options and set the positional parameters, or to display the names and values of shell variables.

set [--abefhkmnptuvxBCEHPT] [-o option-name] [argument …] set [+abefhkmnptuvxBCEHPT] [+o option-name] [argument …]

If no options or arguments are supplied, set displays the names and values of all shell variables and functions, sorted according to the current locale, in a format that may be reused as input for setting or resetting the currently-set variables. Read-only variables cannot be reset. In POSIX mode, only shell variables are listed.

When options are supplied, they set or unset shell attributes. Options, if specified, have the following meanings:

-a Each variable or function that is created or modified is given the export attribute and marked for export to the environment of subsequent commands.

And this as well:

Using ‘+’ rather than ‘-’ causes these options to be turned off. The options can also be used upon invocation of the shell. The current set of options may be found in $-.

17

Improving on Silas Paul's answer

exporting the variables on a subshell makes them local to the command.

(export $(cat .env | xargs) && rails c)

1
  • Then you can use this (set -a; source dev.env; set +a; rails c) to also have the benefits of sourcing (e.g. script can execute).
    – wacha
    Commented Apr 1, 2020 at 17:04
17

SAVE=$(set +o | grep allexport) && set -o allexport && . .env; eval "$SAVE"

This will save/restore your original options, whatever they may be.

Using set -o allexport has the advantage of properly skipping comments without a regex.

set +o by itself outputs all your current options in a format that bash can later execute. Also handy: set -o by itself, outputs all your current options in human-friendly format.

1
  • 2
    I would probably exec env -i bash to clear the existing environment before calling eval if you need to unset variables that are only set within .env.
    – b4hand
    Commented Sep 11, 2015 at 19:46
16

Sorry to add yet another answer but because it's simplistic and works in many cases, try:

export $(< ~/my/.env)
1
  • This will be problematic in case the .env file contains anything other than key-value pairs like x=y. Commented Nov 25 at 20:57
15

If env supports the -S option one may use newlines or escape characters like \n or \t (see env):

env -S "$(cat .env)" command

.env file example:

KEY="value with space\nnewline\ttab\tand
multiple
lines"

Test:

env -S "$(cat .env)" sh -c 'echo "$KEY"'
14

Here's my variant:

  with_env() {
    (set -a && . ./.env && "$@")
  }

compared with the previous solutions:

  • it does not leak variables outside scope (values from .env are not exposed to caller)
  • does not clobber set options
  • returns exit code of the executed command
  • uses posix compatible set -a
  • uses . instead of source to avoid bashism
  • command is not invoked if .env loading fails
with_env rails console
1
  • You can also run inline (the variables are exposed to your current terminal session): set -a && . ./.env && "$@" && echo "your comand here" Commented Apr 18, 2020 at 0:15
14
+50

Use shdotenv

dotenv support for shell and POSIX-compliant .env syntax specification
https://github.com/ko1nksm/shdotenv

eval "$(shdotenv)"

Usage

Usage: shdotenv [OPTION]... [--] [COMMAND [ARG]...]

  -d, --dialect DIALECT  Specify the .env dialect [default: posix]
                           (posix, ruby, node, python, php, go, rust, docker)
  -s, --shell SHELL      Output in the specified shell format [default: posix]
                           (posix, fish)
  -e, --env ENV_PATH     Location of the .env file [default: .env]
                           Multiple -e options are allowed
  -o, --overload         Overload predefined environment variables
  -n, --noexport         Do not export keys without export prefix
  -g, --grep PATTERN     Output only those that match the regexp pattern
  -k, --keyonly          Output only variable names
  -q, --quiet            Suppress all output
  -v, --version          Show the version and exit
  -h, --help             Show this message and exit

Requirements

shdotenv is a single file shell script with embedded awk script.

  • POSIX shell (dash, bash, ksh, zsh, etc)
  • awk (gawk, nawk, mawk, busybox awk)
3
  • Awesome tool and great attention to details. Thanks!! Commented Jan 4, 2022 at 15:59
  • @PierreGramme Using a dedicated tool running at least two forks for resolving a problem of understanding a concept reduced in one command seem a little overkill! Commented Jan 9, 2022 at 11:59
  • 3
    @FHauri Maybe an overkill, but this question has 43 different answers: was it really such a simple problem? In my use case I have a .env file written in Python dialect and apply it to Bash. Can't simply use source due to different conventions for managing spaces etc. That tool and its analysis of differences was definitely useful for me Commented Jan 9, 2022 at 21:24
12

Some notes:

  1. The ".env" file should have an "LF" end-of-line sequence.
  2. Avoid using dynamic values in environment variables, such as variable1=$variable2@$variable3
  3. Avoid using a quotation (") in environment variables vavlue, such as variable="value"

This is the best and shortest answer

source .env && export $(cut -d= -f1 < .env)
11

Simpler:

  1. grab the content of the file
  2. remove any blank lines (just incase you separated some stuff)
  3. remove any comments (just incase you added some...)
  4. add export to all the lines
  5. eval the whole thing

eval $(cat .env | sed -e /^$/d -e /^#/d -e 's/^/export /')

Another option (you don't have to run eval (thanks to @Jaydeep)):

export $(cat .env | sed -e /^$/d -e /^#/d | xargs)

Lastly, if you want to make your life REALLY easy, add this to your ~/.bash_profile:

function source_envfile() { export $(cat $1 | sed -e /^$/d -e /^#/d | xargs); }

(MAKE SURE YOU RELOAD YOUR BASH SETTINGS!!! source ~/.bash_profile or.. just make a new tab/window and problem solved) you call it like this: source_envfile .env

1
  • 2
    I had to read .env text from gitlab secret variable for a pipeline: Based on your solution this command worked for me: source <( echo $(sed -E -n 's/[^#]+/ &/ p' <(echo "${2}" | tr -d '\r')) );. Somehow gitlab saves the secret variable with a windows carriage return, so I had to trim that with tr -d '\r'.
    – metanerd
    Commented Nov 24, 2017 at 11:21
9
t=$(mktemp) && export -p > "$t" && set -a && . ./.env && set +a && . "$t" && rm "$t" && unset t

How it works

  1. Create temp file.
  2. Write all current environment variables values to the temp file.
  3. Enable exporting of all declared variables in the sources script to the environment.
  4. Read .env file. All variables will be exported into current environment.
  5. Disable exporting of all declared variables in the sources script to the environment.
  6. Read the contents of the temp file. Every line would have declare -x VAR="val" that would export each of the variables into environment.
  7. Remove temp file.
  8. Unset the variable holding temp file name.

Features

  • Preserves values of the variables already set in the environment
  • .env can have comments
  • .env can have empty lines
  • .env does not require special header or footer like in the other answers (set -a and set +a)
  • .env does not require to have export for every value
  • one-liner
1
  • I really appreciate your solution. In most projects you have .env files with comments, spaces, no export statement etc. Pretty nice! Commented Feb 17, 2021 at 7:45
8

You can use your original script to set the variables, but you need to call it the following way (with stand-alone dot):

. ./minientrega.sh

Also there might be an issue with cat | while read approach. I would recommend to use the approach while read line; do .... done < $FILE.

Here is a working example:

> cat test.conf
VARIABLE_TMP1=some_value

> cat run_test.sh
#/bin/bash
while read line; do export "$line";
done < test.conf
echo "done"

> . ./run_test.sh
done

> echo $VARIABLE_TMP1
some_value
1
  • Unlike most other answers, this solution doesn't eval test.conf as a script file. That makes it better. It's safer to not allow scripting unless you actually need it, especially if someone don't realize that's what's going on (or forgets).
    – meustrus
    Commented May 4, 2020 at 16:32
8

I work with docker-compose and .env files on Mac, and wanted to import the .env into my bash shell (for testing), and the "best" answer here was tripping up on the following variable:

.env

NODE_ARGS=--expose-gc --max_old_space_size=2048

Solution

So I ended up using eval, and wrapping my env var defs in single quotes.

eval $(grep -v -e '^#' .env | xargs -I {} echo export \'{}\')

Bash Version

$ /bin/bash --version
GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin18)
Copyright (C) 2007 Free Software Foundation, Inc.
7

My requirements were:

  • simple .env file without export prefixes (for compatibility with dotenv)
  • supporting values in quotes: TEXT="alpha bravo charlie"
  • supporting comments prefixed with # and empty lines
  • universal for both mac/BSD and linux/GNU

Full working version compiled from the answers above:

  set -o allexport
  eval $(grep -v '^#' .env | sed 's/^/export /')
  set +o allexport
1
  • 4
    what's the point of "-o allexport" if you prepend them with "export" anyway?
    – il--ya
    Commented Jul 23, 2019 at 21:29
6

Building on other answers, here is a way to export only a subset of lines in a file, including values with spaces like PREFIX_ONE="a word":

set -a
. <(grep '^[ ]*PREFIX_' conf-file)
set +a
5

I have issues with the earlier suggested solutions:

  • @anubhava's solution makes writing bash friendly configuration files very annoying very fast, and also - you may not want to always export your configuration.
  • @Silas Paul solution breaks when you have variables that have spaces or other characters that work well in quoted values, but $() makes a mess out of.

Here is my solution, which is still pretty terrible IMO - and doesn't solve the "export only to one child" problem addressed by Silas (though you can probably run it in a sub-shell to limit the scope):

source .conf-file
export $(cut -d= -f1 < .conf-file)
5

My .env:

#!/bin/bash
set -a # export all variables

#comments as usual, this is a bash script
USER=foo
PASS=bar

set +a #stop exporting variables

Invoking:

source .env; echo $USER; echo $PASS

Reference https://unix.stackexchange.com/questions/79068/how-to-export-variables-that-are-set-all-at-once

0
5

My version :

I print the file, remove commented lines, emptylines, and I split key/value from "=" sign. Then I just apply the export command.

The advantage of this solution is the file can contain special chars in values, like pipes, html tags, etc., and the value doesn't have to be surrounded by quotes, like a real properties file.

# Single line version
cat myenvfile.properties | grep -v '^#' | grep '=' | while read line; do IFS=\= read k v <<< $line; export $k="$v"; done

# Mutliline version:
cat myenvfile.properties | grep -v '^#' | grep '=' | while read line; do 
  IFS=\= read k v <<< $line
  export $k="$v"
done

5

Here's my take on this. I had the following requirements:

  • Ignore commented lines
  • Allow spaces in the value
  • Allow empty lines
  • Ability to pass a custom env file while defaulting to .env
  • Allow exporting as well as running commands inline
  • Exit if env file doesn't exist
source_env() {
  env=${1:-.env}
  [ ! -f "${env}" ] && { echo "Env file ${env} doesn't exist"; return 1; }
  eval $(sed -e '/^\s*$/d' -e '/^\s*#/d' -e 's/=/="/' -e 's/$/"/' -e 's/^/export /' "${env}")
}

Usage after saving the function to your .bash_profile or equivalent:

source_env                # load default .env file
source_env .env.dev       # load custom .env file
(source_env && COMMAND)   # run command without saving vars to environment

Inspired by Javier and some of the other comments.

0
4

White spaces in the value

There are many great answers here, but I found them all lacking support for white space in the value:

DATABASE_CLIENT_HOST=host db-name db-user 0.0.0.0/0 md5

I have found 2 solutions that work whith such values with support for empty lines and comments.

One based on sed and @javier-buzzi answer:

source <(sed -e /^$/d -e /^#/d -e 's/.*/declare -x "&"/g' .env)

And one with read line in a loop based on @john1024 answer

while read -r line; do declare -x "$line"; done < <(egrep -v "(^#|^\s|^$)" .env)

The key here is in using declare -x and putting line in double quotes. I don't know why but when you reformat the loop code to multiple lines it won't work — I'm no bash programmer, I just gobbled together these, it's still magic to me :)

3
  • 1
    I had to modify the sed solution to get it to work. But first some explanation: -e is short for --expression, which just tells sed what operations to take. -e /^$/d deletes the empty lines from the output (not the file). -e /^#/d deletes the bash comments (lines that start with #) from the output. 's/.*/declare -x "&"/g' replaces (substitutes) the remaining lines with declare -x "ENV_VAR="VALUE"". When you source this, at least for me, it didn't work. Instead, I had to use source <(sed -e /^$/d -e /^#/d -e 's/.*/declare -x &/g' .env), to remove the extra " wrapper.
    – jcasner
    Commented Apr 10, 2018 at 20:49
  • I don't use ENV_VAR="lorem ipsum", I have ENV_VAR=lorem ipsum, without quotes in the .env file. Now I'm not sure why, but this was probably problematic in other tools that parse this file. And instead of lorem ipsum I have ended with "lorem ipsum" value – with quotes. Thx for the explanations :) Commented Apr 11, 2018 at 6:51
  • 1
    If it was my choice, I wouldn't use ENV_VAR="lorem ipsum" either. In my use case, my hosting provider generates this file based on some configuration options I have set, and they insert the double quotes. So, I am forced to work around it. Thanks for your help here - saved me a lot of time trying to work out the correct sed options myself!
    – jcasner
    Commented Apr 13, 2018 at 13:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.