<!--
  canonical-url: https://www.avonture.be/blog/direnv
  published:     2026-11-26
  This is a static plain-Markdown mirror generated at build time.
  Visit the canonical URL above for the fully rendered page, with images and interactive components.
-->

# 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.

---
![direnv — Stop Typing source .env, Let Your Shell Do It](/img/v2/direnv.webp)

**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:

```bash
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`:

```bash
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:

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

Run it once:

```bash
direnv allow
```

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

```bash
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:

```bash
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.

**Dockerfile**

```docker
FROM ubuntu:24.04

ENV DEBIAN_FRONTEND=noninteractive

# Ubuntu's docker image only enables "main" + "restricted" by default;
# direnv lives in "universe".
RUN sed -i 's/^Components: main restricted$/Components: main restricted universe multiverse/' \
        /etc/apt/sources.list.d/ubuntu.sources && \
    apt-get update && \
    apt-get install -y \
        direnv && \
    rm -rf /var/lib/apt/lists/*

# Hook direnv into bash — the exact one-liner from this article
RUN echo 'eval "$(direnv hook bash)"' >> /root/.bashrc

# Build the exact my-api project from "The Docker Compose use case" — an
# .envrc left deliberately UN-allowed, so the "blocked" message is the
# first thing you see, exactly like the article describes
RUN mkdir -p /root/my-api && \
    printf 'dotenv\n' > /root/my-api/.envrc && \
    printf '%s\n' \
        'DB_HOST=localhost' \
        'DB_PORT=5432' \
        'DB_NAME=myapp_dev' \
        'DB_USER=dev' \
        'DB_PASSWORD=changeme' \
        '' \
        'APP_PORT=8080' \
        'APP_DEBUG=true' \
        > /root/my-api/.env.example && \
    cp /root/my-api/.env.example /root/my-api/.env && \
    printf 'services:\n  db:\n    image: postgres:16\n    environment:\n      POSTGRES_PASSWORD: ${DB_PASSWORD}\n      POSTGRES_DB: ${DB_NAME}\n' \
        > /root/my-api/compose.yaml

WORKDIR /root

# Signal clearly that this shell runs inside a container
RUN echo "PS1='\n\e[0;33m🐳 \e[0;36m\$(whoami)\e[0m \w # '" >> /root/.bashrc

CMD ["/bin/bash", "-i"]
```

Build and run it:

```bash
$ 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:

```bash
$ 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:

```bash
sudo apt install direnv
```

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

For ZSH (add to `~/.zshrc`):

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

For Bash (add to `~/.bashrc`):

```bash
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"
```

## More Demos

### The Docker Compose use case

A typical project structure:

```text
my-api/
  .env          ← actual secrets, git-ignored
  .env.example  ← template committed to git
  .envrc        ← just "dotenv", can be committed
  compose.yaml
```

```example
DB_HOST=localhost
DB_PORT=5432
DB_NAME=myapp_dev
DB_USER=dev
DB_PASSWORD=changeme

APP_PORT=8080
APP_DEBUG=true
```

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

```yaml
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:

```text
.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:

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

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

```bash
# .envrc
dotenv .env.staging
```

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

### What to commit

The safe pattern:

```text
.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](/blog/bash-load-env). The difference:

|                        | Manual `source .env` | direnv |
| ---------------------- | -------------------- | ------ |
| Loads on `cd`          | No                   | Yes    |
| Unloads on `cd` out    | No                   | Yes    |
| Prevents env leakage   | No                   | Yes    |
| Works in all terminals | Needs re-sourcing    | Yes    |
| Supports `PATH_add`    | No                   | Yes    |

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](/blog/zsh-install) on this blog, direnv integrates directly into your `.zshrc` with the single `eval "$(direnv hook zsh)"` line shown above.
