Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Parse a .env (dotenv) file directly using BASH
# Pass the env-vars to MYCOMMAND
eval $(egrep -v '^#' .env | xargs) MYCOMMAND
# … or ...
# Export the vars in .env into your shell:
export $(egrep -v '^#' .env | xargs)
@kowalk

This comment has been minimized.

Show comment Hide comment
@kowalk

kowalk Feb 16, 2018

If you want just set a single variable in your script just use code below:
MY_VAR=$(grep MY_VAR .env | xargs)
IFS='=' read -ra MY_VAR <<< "$MY_VAR"
MY_VAR=${MY_VAR[1]}

kowalk commented Feb 16, 2018

If you want just set a single variable in your script just use code below:
MY_VAR=$(grep MY_VAR .env | xargs)
IFS='=' read -ra MY_VAR <<< "$MY_VAR"
MY_VAR=${MY_VAR[1]}

@rafaelbeckel

This comment has been minimized.

Show comment Hide comment
@rafaelbeckel

rafaelbeckel Mar 17, 2018

read_var() {
    VAR=$(grep $1 $2 | xargs)
    IFS="=" read -ra VAR <<< "$VAR"
    echo ${VAR[1]}
}

MY_VAR=$(read_var MY_VAR .env)
read_var() {
    VAR=$(grep $1 $2 | xargs)
    IFS="=" read -ra VAR <<< "$VAR"
    echo ${VAR[1]}
}

MY_VAR=$(read_var MY_VAR .env)
@desprit

This comment has been minimized.

Show comment Hide comment
@desprit

desprit Mar 26, 2018

MY_VAR=$(grep MY_VAR .env | xargs)
MY_VAR=${MY_VAR#*=}

dunno about possible drawbacks though

desprit commented Mar 26, 2018

MY_VAR=$(grep MY_VAR .env | xargs)
MY_VAR=${MY_VAR#*=}

dunno about possible drawbacks though

@pronebird

This comment has been minimized.

Show comment Hide comment
@pronebird

pronebird May 27, 2018

It won't work if you have spaces, i.e FOO="BAR BUZ" will be returned without quotes from xargs

pronebird commented May 27, 2018

It won't work if you have spaces, i.e FOO="BAR BUZ" will be returned without quotes from xargs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment