Skip to content

Instantly share code, notes, and snippets.

@peterwwillis
Created May 29, 2019 14:33
Show Gist options
  • Save peterwwillis/8e05124dfd364346bdac4f3501ad74be to your computer and use it in GitHub Desktop.
Save peterwwillis/8e05124dfd364346bdac4f3501ad74be to your computer and use it in GitHub Desktop.
Load environment variables from a file with key=value pairs and optionally execute a program
#!/bin/sh
# defaultenv.sh - Load environment variable defaults and run programs
set -e
[ x"$DEBUG" = "x1" ] && set -x
_load_envrc () {
local file="$1"; shift
if [ -r "$file" ] ; then
# Bourne shell limits how we can test and set env vars, so here I'm
# just writing the .env file to a new file, then reading the file into
# a while loop, and using `env` and `grep` to see if the KEY might already
# be set. It's pretty terrible, but this is the best way I could figure
# to do this with Bourne shell.
TMP=$(mktemp)
cat "$file" | grep -v '^$\|^[[:space:]]*#' | sed -e 's/^export[[:space:]]\+//' | grep -i '^[a-z0-9_]\+=' > $TMP
while read LINE ; do
KEY="${LINE%%=*}"
VALUE="${LINE#*=}"
if ! env | grep -q -e "^$KEY=" ; then
echo "Setting $file env '$KEY=$VALUE'" 2>&1
export "$KEY"="$VALUE"
fi
done < $TMP
rm -f $TMP
else
echo "Error: cannot read envrc '$file'" ; exit 1
fi
}
if [ $# -eq 0 ] \
&& [ -n "$ENVRC" ] \
&& [ -r "$ENVRC" ]
then
_load_envrc "$ENVRC"
elif [ $# -gt 0 ] ; then
_load_envrc "$1"
shift
else
echo "Usage: $0 [ENVRC [ARGS [..]]]"
echo ""
echo "Pass a file ENVRC (made up of KEY=VALUE lines) and they will be set as environment variables,"
echo "but only if an existing KEY isn't already set in the environment."
echo "If ARGS are passed, they are executed by the shell."
echo "If no arguments are passed, the ENVRC environment variable will be checked for the file to read."
exit 1
fi
if [ $# -gt 0 ] ; then
exec "$@"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment