How to automatically load and unload .env file with variables

Is it possible to load an .env file when accessing the directory they are in and unload these variables when changing to another directory?


Yes with bash.. This will change directory to the specified directory as normal and if a .env file exists there it will source it. If you add this snippet to your users .bashrc and source it.

function cd() {
    new_directory="$*";
    if [ $# -eq 0 ]; then
        new_directory=${HOME};
    fi;
    builtin cd "${new_directory}"

    if [ -f .env ];
    then
        source .env
    fi
}