Skip to content

Instantly share code, notes, and snippets.

@andrenarchy
Last active March 25, 2018 14:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrenarchy/fe314dca781c2fb36f4fc3dd9dfcf707 to your computer and use it in GitHub Desktop.
Save andrenarchy/fe314dca781c2fb36f4fc3dd9dfcf707 to your computer and use it in GitHub Desktop.
Export variables from an .env file
# dotenvexport FILE
#
# Exports all vars from a .env file without overwriting existing variables (see https://docs.docker.com/compose/env-file/)
dotenvexport () {
FILE=$1
OLDIFS="$IFS"
IFS=$'\n'
for line in $(cat $FILE | grep -vE "^(#|\s*$)"); do
VAR=${line%%=*}
if ! [[ -v $VAR ]]; then
export "$line"
fi
done
IFS="$OLDIFS"
}
# dotenvrun FILE COMMAND [ARG1 ...]
#
# Load all vars from a .env file FILE and run COMMAND with optional arguments.
# The command is run in a subshell so the environment of the currently running
# shell is not cluttered up.
dotenvrun () {
FILE=$1
COMMAND=${@:2}
(dotenvexport $FILE && bash -c "$COMMAND")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment