Skip to content

Instantly share code, notes, and snippets.

@genyrosk
Created June 10, 2023 23:20
Show Gist options
  • Save genyrosk/0001fd867f7cad3661fdb8402f5ff4b8 to your computer and use it in GitHub Desktop.
Save genyrosk/0001fd867f7cad3661fdb8402f5ff4b8 to your computer and use it in GitHub Desktop.
Some short helper bash functions to load, set and unset environment variables from .env.* files
#!/usr/bin/env bash
#
# Load / Unset env vars from file
#
function get_env_file() {
local env=$1
local envfile=$([ -z "$env" ] && echo ".env" || echo ".env.${env}")
echo $envfile
}
function load_envfile() {
local env=$1
local envfile=$(get_env_file $env)
if [ ! -f $envfile ]; then
echo "File ${envfile} does not exist"
kill -INT $$
fi
echo "Loading env vars from ${envfile}"
echo "--------------------------------------"
cat ${envfile}
export $(grep -v '^#' ${envfile} | xargs)
}
function unset_envfile() {
local env=$1
local envfile=$(get_env_file $env)
if [ ! -f $envfile ]; then
echo "File ${envfile} does not exist"
kill -INT $$
fi
echo "Unsetting env vars from ${envfile}"
unset $(grep -v '^#' ${envfile} | sed -E 's/(.*)=.*/\1/' | xargs)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment