Theme:
Tidbit
  • technical|
  • productivity

Loading .env files with no dependencies

Guy Waldman's ProfileGuy Waldman
July 26, 2024

#Problem

You have environment variables that you want to use in your project, and don't want to manually export them (and expose them in your shell history).
So you create a local (git ignoreD!) .env file that you wish to load into your BASH or ZSH shell session, that looks like so:
MY_SECRET="super-secret-value"
MY_OTHER_SECRET="other-secret-value"
You want a simple script which will load these variables into your shell session, and you don't want to install any dependencies to do this (e.g., dotenv-cli.

#Solution

# Loads environment variables from a file into the current shell.
# Usage: dotenv <env_file_path>
function dotenv {
	env_file_path="$1"

	# Bail out if the file doesn't exist.
	if [ ! -f "$env_file_path" ]; then
		echo "Error: File '$env_file_path' does not exist." >&2
		return 1
	fi

	echo "Loading environment variables from '$env_file_path...'"
	# `sllexport`: Each variable or function that is created or modified is given the export attribute and marked for export to the environment of subsequent commands.
	set -o allexport
	source <(sed -e "s/\r//" -e '/^#/d;/^\s*$/d' -e "s/'/'\\\''/g" -e "s/=\(.*\)/=\"\1\"/g" "${env_file_path}")
	set +o allexport

	# Display the environment variables that were loaded.
	env_vars=$(cat "$env_file_path" | grep -E '^[A-Z0-9_]+\s*=' | cut -d = -f 1 | tr '\n' ' ')
	env_vars=($(echo $env_vars))
	echo "Environment variables loaded from '$env_file_path': $(join_by ', ' $env_vars)"
}

#References

https://gist.github.com/mihow/9c7f559807069a03e302605691f85572?permalink_comment_id=4287253#gistcomment-4287253

Related content

    • technical|
    • productivity
    Git hooks for fun & profit
    Post
    August 9, 2022
    Using git hooks for developer workflow automation
    • technical|
    • web
    Web page to PDF
    Post
    April 3, 2021
    Trying to generate a PDF from a web page is not as straightforward as you would think
    • technical|
    • web|
    • react
    Button with a ripple effect
    Post
    October 9, 2019
    Creating a material design style button with a ripple effect - includes a React example
    • technical
    Complex return types in TypeScript
    Tidbit
    July 17, 2024
    Resolving complex return types in TypeScript by declaring overloads of function signatures
    • productivity|
    • ai
    Introducing: magic-cli
    Post
    July 16, 2024
    A command line utility that will make you a magician in the terminal