Skip to content
Posted on:January 4, 2023 at 07:00 AM

Direnv with .env file

Direnv with .env file

Direnv provides a great way to control .env file which controls the environment variables for the project.

Direnv start supporting .env files from v2.31.0

1. Install

1.1 Install on Mac

  1. Use home brew to install
  2. Hook into your shell: https://direnv.net/docs/hook.html
  3. Set upt the toml file to recognize the .env file at the root of your projects
    1. Create direnv.toml file at $HOME/.config/direnv/direnv.toml
    2. add thhe block to load the .env
## step 1. install with homebrew
brew install direnv
direnv --version
2.32.1

## step 2. add this in your .zshrc
eval "$(direnv hook zsh)"

## step 3. make direnv toml file
cd ~
mkdir .config/direnv/
nano .config/direnv/direnv.toml

### then add this block in direnv.toml file
[global]
load_dotenv = true

1.2 Install on Ubuntu

  1. Don’t use apt to install on ubuntu 20.04. It’s default version is 2.21.2 which doesn’t have dotenv loading feature. It came out after v2.31.0: https://direnv.net/docs/installation.html
  2. Install with binary script:
  3. Hook into your shell: https://direnv.net/docs/hook.html
  4. Set up the toml file to recognize the .env file at the root of your projects
## step 1.
curl -sfL https://direnv.net/install.sh | bash

# this will download direnv file to ~/.local/bin directory

## step 2. add this in your .bashrc
eval "$(direnv hook bash)"

## also add apth to ~/.local/bin
export PATH=~/.local/bin:$PATH

## step 3. make direnv toml file
cd ~
mkdir .config/direnv/
nano .config/direnv/direnv.toml

### then add this block in direnv.toml file
[global]
load_dotenv = true

2. Usage

After setting all this, when you cd into your directory, direnv will ask you

direnv: error /home/ubuntu/your_project/.env is blocked. Run `direnv allow` to approve its content
cd your_project
cat .env
FOO=BAR

Then run direnv allow to recognize environment variables in this file:

env | grep FOO
FOO=BAR

Everytime there is an update in .env file, direnv will ask you to allow it or disallow it. You can run direnv allow to reflect the changes in .env file.

Web Analytics