Shell script to load variables from .env (dotenv) files.
#!/bin/sh
#
# Load variables from '.env' files
#
# Usage:
#
# To inject '.env' variables and run a command:
# dotenv my_command param1 param2
#
# To inject '.env' configs into the current shell:
# . dotenv
#
# Original code by madcoda/dotenv-shell
# <https://github.com/madcoda/dotenv-shell>
#
set -e
is_comment() {
case "$1" in
\#*)
if [ "$VERBOSE" = 1 ]; then
echo "Skip: $1" >&2
fi
return 0
;;
esac
return 1
}
export_env_vars() {
while IFS='=' read -r key temp; do
if is_comment "$key"; then
continue
fi
value=$(eval echo "$temp")
eval export "$key='$value'";
done < .env
}
# inject .env configs into the shell
if [ -r .env ] && [ -f .env ]; then
export_env_vars
else
echo "no '.env' file to load" >&2
fi
# then run whatever commands you like
if [ $# -gt 0 ]; then
exec "$@"
fi