Skip to content

Instantly share code, notes, and snippets.

@mariocesar

mariocesar/README.md

Last active Apr 30, 2021
Embed
What would you like to do?
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