Tidbit
- technical|
- productivity
Loading .env files with no dependencies
![Guy Waldman's Profile](/_next/image?url=%2Fprofile.png&w=640&q=75)
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!)
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
Related content
- technical|
- productivity
Git hooks for fun & profitPostAugust 9, 2022Using git hooks for developer workflow automation- technical|
- web
Web page to PDFPostApril 3, 2021Trying to generate a PDF from a web page is not as straightforward as you would think- technical|
- web|
- react
Button with a ripple effectPostOctober 9, 2019Creating a material design style button with a ripple effect - includes a React example- technical
Complex return types in TypeScriptTidbitJuly 17, 2024Resolving complex return types in TypeScript by declaring overloads of function signatures- productivity|
- ai
Introducing: magic-cliPostJuly 16, 2024A command line utility that will make you a magician in the terminal