Last active
March 25, 2018 14:51
-
-
Save andrenarchy/fe314dca781c2fb36f4fc3dd9dfcf707 to your computer and use it in GitHub Desktop.
Export variables from an .env file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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