Skip to content

Instantly share code, notes, and snippets.

@eddiecorrigall
Created January 20, 2022 19:11
Show Gist options
  • Save eddiecorrigall/4eba68e402a3d75dd76691878d66dee7 to your computer and use it in GitHub Desktop.
Save eddiecorrigall/4eba68e402a3d75dd76691878d66dee7 to your computer and use it in GitHub Desktop.
CLI tool to load dot env (.env) file for a program
#!/bin/bash
set -e
# References:
# - Syntax Rules: https://docs.docker.com/compose/env-file/#syntax-rules
function ltrim() {
# Trim whitespace to the left (leading whitespace)
local text="$1"
echo "${text#"${text%%[![:space:]]*}"}"
}
function rtrim() {
# Trim whitespace to the right (trailing whitespace)
local text="$1"
echo "${text%"${text##*[![:space:]]}"}"
}
function parse_and_export_line() {
# Parse a line of a dot env file
# Define the first argument of the function
local line="$1"
# Trim leading whitespace from line
line="$(ltrim "$line")"
if [ -z "$line" ]; then
# If line is empty,
# then the line can be ignored.
return
fi
if [ "${line::1}" = "#" ]; then
# If first character of left-trimmed line is a comment (#),
# then this is a comment
return
fi
local key
# Select the first field, delimeted by equals (=)
key="$(echo "$line" | cut -d '=' -f 1)"
# Trim trailing whitespace from name
key="$(rtrim "$key")"
local value
# Select all text except for the first field, delimited by equals (=)
value="$(echo "$line" | cut -d '=' -f 1 --complement)"
# Export the key-value pair as an environment variable
eval export "$key='$value'";
}
SCRIPT_NAME="$0"
function usage() {
echo "USAGE: $SCRIPT_NAME <DOT_ENV_PATH> <PROGRAM>"
echo "Examples:"
echo -e "\t$SCRIPT_NAME app.env 'env | grep VARIABLE_IN_DOT_ENV'"
echo -e "\t$SCRIPT_NAME app.env 'node app'"
}
# Define the first argument of the script
DOT_ENV_PATH="$1"
if [ -z "${DOT_ENV_PATH}" ]; then
echo 'ERROR: Missing first argument for dot env path!' > /dev/stderr
usage
exit 1
fi
# Define the second argument of the script
PROGRAM="$2"
if [ -z "${PROGRAM}" ]; then
echo 'ERROR: Missing second argument for program!' > /dev/stderr
usage
exit 1
fi
# For each line of the input file
while read -r line; do
# Parse and export each line of the dot env file
parse_and_export_line "$line"
done < "$DOT_ENV_PATH"
# Now run the program with these environment variables
eval "$PROGRAM"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment