Skip to main content

direnv — Stop Typing `source .env`, Let Your Shell Do It

direnv automatically loads and unloads environment variables when you cd into a project. Different database passwords per project, no manual source commands, and nothing ever leaks into your global shell.

· 7 min read
View raw
Christophe
Markdown, WSL and Docker lover ~ Insatiable curious.
Claude Code
AI Assistant
Cet article existe aussi en français — lire la version française.

direnv — Stop Typing source .env, Let Your Shell Do It

⚡
TL;DR

direnv hooks into your shell and automatically runs source .env (or any command in an .envrc file) when you cd into a project — and undoes it when you leave. Each project gets its own environment variables with no global pollution, no manual sourcing, and no risk of carrying one project's secrets into another.

Every Docker project has a .env file. And every time you open a new terminal and forget to run source .env, something fails. You set DB_PASSWORD in the shell, switch to another project, and now your second project's Docker Compose is picking up the wrong database credentials.

direnv solves this permanently. You cd in — variables are loaded. You cd out — they're gone.

Seeing direnv in Action​

Create a project directory and add an .envrc file:

>user@machine: ~/yourproject

mkdir my-api && cd my-api echo "dotenv" > .envrc

The single word dotenv tells direnv to load the .env file in the same directory. Now create the .env:

>user@machine: ~/yourproject

cp .env.example .env # template shown in "The Docker Compose use case" below

edit .env with your local values

The first time you enter a directory with a new .envrc, direnv asks for explicit permission:

>user@machine: ~/yourproject

direnv: error /home/christophe/my-api/.envrc is blocked. Run direnv allow to approve its content.

Run it once:

>user@machine: ~/yourproject

direnv allow

From that point on, entering the directory loads the variables automatically:

>user@machine: ~/yourproject

cd my-api direnv: loading ~/my-api/.envrc direnv: export +APP_DEBUG +APP_PORT +DB_HOST +DB_NAME +DB_PASSWORD +DB_PORT +DB_USER

And leaving unloads them:

>user@machine: ~/yourproject

cd .. direnv: unloading

The allow step is intentional

direnv requires explicit approval (direnv allow) each time .envrc changes. This prevents a cloned repository from automatically running arbitrary code in your shell without your knowledge.

That's the entire effect — the install behind it is two commands, covered next.

Seeing It in Action with Docker​

Before hooking direnv into your own ~/.bashrc, try the exact flow above in a throwaway container — the my-api project (.envrc, .env, compose.yaml) is already built, deliberately left un-allowed so the "blocked" message is the first thing you see.

Why Docker first?

The Dockerfile below installs direnv, hooks it into bash, and builds the my-api project from the "Docker Compose use case" section further down. Nothing on your own machine changes.

Build and run it:

>user@machine: ~/direnv-demo

$ docker build -t direnv-demo . [+] Building 11.4s (6/6) FINISHED ✔ exporting to image

$ docker run --rm -it direnv-demo 🐳 root ~ # cd my-api direnv: error /root/my-api/.envrc is blocked. Run direnv allow to approve its content

Exactly the "blocked" message from above. Approve it, then leave and come back:

>🐳 root ~/my-api #

$ direnv allow direnv: loading ~/my-api/.envrc direnv: export +APP_DEBUG +APP_PORT +DB_HOST +DB_NAME +DB_PASSWORD +DB_PORT +DB_USER

$ cd .. direnv: unloading

$ cd my-api direnv: loading ~/my-api/.envrc direnv: export +APP_DEBUG +APP_PORT +DB_HOST +DB_NAME +DB_PASSWORD +DB_PORT +DB_USER

Loaded on the way in, unloaded on the way out, reloaded the moment you're back — the whole pitch of this article, live, before touching your own shell config.

Why It Works​

  • direnv hooks your shell so every cd re-checks the current and parent directories for an .envrc file and re-evaluates it — no polling, no background daemon.
  • The minimal .envrc is a single word, dotenv — there's nothing to write from scratch for the common case.
  • PATH_add is a direnv built-in that prepends a path to $PATH and removes it again on exit. It's safer than export PATH="./scripts:$PATH" because direnv tracks exactly what it added, and can undo it cleanly.

Install​

On Ubuntu / Debian / WSL:

>user@machine: ~/yourproject

sudo apt install direnv

Then hook it into your shell. This is a one-time setup:

For ZSH (add to ~/.zshrc):

>user@machine: ~/yourproject

echo 'eval "$(direnv hook zsh)"' >> ~/.zshrc source ~/.zshrc

For Bash (add to ~/.bashrc):

>user@machine: ~/yourproject

echo 'eval "$(direnv hook bash)"' >> ~/.bashrc source ~/.bashrc

That's the entire installation. direnv is now watching every directory change.

What goes in .envrc​

The minimal .envrc is just dotenv:

dotenv

But .envrc is a shell script. You can do more, including PATH_add:

# Load all variables from .env
dotenv
# Add project scripts to PATH
PATH_add ./scripts
# Set a project-specific variable directly
export APP_NAME="my-api"

This configuration file sets up the development environment by loading variables from a .env file, adding a scripts directory to the system PATH so commands there can be run easily, and defining a project name variable that will be available to all processes.

More Demos​

The Docker Compose use case​

A typical project structure:

my-api/
.env ← actual secrets, git-ignored
.env.example ← template committed to git
.envrc ← just "dotenv", can be committed
compose.yaml
DB_HOST=localhost
DB_PORT=5432
DB_NAME=myapp_dev
DB_USER=dev
DB_PASSWORD=changeme
APP_PORT=8080
APP_DEBUG=true

This is a configuration file that stores environment variables for a development application. It defines the database connection details (host, port, database name, credentials) and basic app settings like the port the app runs on and whether debugging is enabled.

Your compose.yaml references variables with ${DB_PASSWORD} — Docker Compose reads from the environment, which direnv has already loaded:

services:
db:
image: postgres:16
environment:
POSTGRES_PASSWORD: ${DB_PASSWORD}
POSTGRES_DB: ${DB_NAME}

When you cd into the project, docker compose up just works. When you switch projects, the old variables are gone and the new project's variables take their place.

Multiple environments​

Direnv works perfectly with multiple .env files. A common pattern:

.env ← local dev (git-ignored)
.env.staging ← staging values (may be committed if non-sensitive)
.env.example ← template (always committed)

To temporarily switch environment without changing .envrc, let Docker Compose read the other file for that one command:

>user@machine: ~/yourproject

docker compose --env-file .env.staging up

Or simpler — adjust .envrc directly and re-allow:

# .envrc
dotenv .env.staging

Under the Hood (skip this if you just want to use it)​

What to commit​

The safe pattern:

.gitignore entries:
.env
.env.local
.env.*.local

Committed:
.envrc ← safe, only contains "dotenv" or non-secret logic
.env.example ← documents all required variables, no real values

Never commit .env with real secrets

.envrc itself is safe to commit if it only contains dotenv or PATH_add calls. But .env with actual passwords or API keys must stay in .gitignore. Always.

direnv and VSCode​

VSCode's integrated terminal inherits the shell environment. If you open VSCode from a terminal where direnv has already loaded the variables for a project, they're available in the integrated terminal automatically.

If you launch VSCode directly (from the Dock, Spotlight, or a desktop shortcut), the integrated terminal starts fresh without your shell hooks. The fix: always open projects with code . from a terminal where direnv is active.

Comparison with the manual approach​

You may already use a pattern like the one described in Bash — Loading environment variables from a file. The difference:

Manual source .envdirenv
Loads on cdNoYes
Unloads on cd outNoYes
Prevents env leakageNoYes
Works in all terminalsNeeds re-sourcingYes
Supports PATH_addNoYes

The manual approach is fine for a single-project workflow. Once you work across multiple projects in the same terminal session, direnv becomes indispensable.

Conclusion​

direnv is one of those tools that feels obvious the moment you use it. You stop thinking about environment setup and start focusing on the actual work. Each project carries its own context, and switching between them is frictionless.

Set it up once, add dotenv to .envrc, and never type source .env again.

Already using ZSH?

If you followed the Oh-My-ZSH setup on this blog, direnv integrates directly into your .zshrc with the single eval "$(direnv hook zsh)" line shown above.


Was this article helpful?
Did you try the steps in this article?