Score:0

How to automatically load and unload .env file with variables

br flag

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

za flag
I suggest taking a look at [Direnv](https://direnv.net/) also on [Github](https://github.com/direnv/direnv).
Artur Meinild avatar
vn flag
This could use some more explanation for the actual solution.
Score:1
ph flag

With zsh:

: ${ZSH_DOTENV_FILE:=".env"}

#
# Source local '.env' file (if any).
#
source_env_file() {
  if [[ -f "${ZSH_DOTENV_FILE}" ]]; then
    >&2 echo "Auto-sourcing ${ZSH_DOTENV_FILE} file"
    source "${ZSH_DOTENV_FILE}"
  fi
}

# Hook our function so that it gets automatically executed whenever we `cd`
# See special `chpwd` hook function: https://zsh.sourceforge.io/Doc/Release/Functions.html
autoload -U add-zsh-hook
add-zsh-hook chpwd source_env_file

If you use the ohmyzsh framework, then you could also use this plugin: dotenv (which essentially does the same).

Score:1
in flag

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
}
Score:0
br flag

If you want load .env while opening a new tab

function loadenv() {
    if [ -f .env ];
    then
        source .env
    fi  
}

loadenv

function cd() {
    builtin cd $@
    loadenv                                                                                                                                                            
}
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.