Theme:
Tidbit
  • technical|
  • productivity

Loading .env files with no dependencies

Guy Waldman's ProfileGuy Waldman
July 26, 2024
Time to read:
2 minutes

#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:
1MY_SECRET="super-secret-value" 2MY_OTHER_SECRET="other-secret-value" 3
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

1# Loads environment variables from a file into the current shell. 2# Usage: dotenv <env_file_path> 3function dotenv { 4 env_file_path="$1" 5 6 # Bail out if the file doesn't exist. 7 if [ ! -f "$env_file_path" ]; then 8 echo "Error: File '$env_file_path' does not exist." >&2 9 return 1 10 fi 11 12 echo "Loading environment variables from '$env_file_path...'" 13 # `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. 14 set -o allexport 15 source <(sed -e "s/\r//" -e '/^#/d;/^\s*$/d' -e "s/'/'\\\''/g" -e "s/=\(.*\)/=\"\1\"/g" "${env_file_path}") 16 set +o allexport 17 18 # Display the environment variables that were loaded. 19 env_vars=$(cat "$env_file_path" | grep -E '^[A-Z0-9_]+\s*=' | cut -d = -f 1 | tr '\n' ' ') 20 env_vars=($(echo $env_vars)) 21 echo "Environment variables loaded from '$env_file_path': $(join_by ', ' $env_vars)" 22} 23

#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