Skip to content

Instantly share code, notes, and snippets.

@mariocesar
Last active April 30, 2021 02:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mariocesar/aebf86c05150fb6183004f7d4bcbe3fe to your computer and use it in GitHub Desktop.
Save mariocesar/aebf86c05150fb6183004f7d4bcbe3fe to your computer and use it in GitHub Desktop.
Useful shell function to load .env files in the terminal session

Load environment variables using .env files

You can add the following functions for your shell, loadenv will search for .env file if found will export all to the shell session with unloadenv will unset the variables so you can start again, reloadenv will reread the .env file.

function loadenv {
    test -f .env || echo "No .env file in the working directory"
    oldenv=$(env|sort)
    export $(grep -v '^#' .env | xargs -d '\n')
    diff <(echo "$oldenv") <(env | sort)
}

function unloadenv {
    test -f .env || echo "No .env file in the working directory"
    oldenv=$(env|sort)
    unset $(grep -v '^#' .env | sed -E 's/(.*)=.*/\1/' | xargs -d '\n')
    diff <(echo "$oldenv") <(env | sort)
}

function reloadenv {
  unloadenv
  loadenv
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment