Skip to content
I replaced activate.sh with direnv

Delete activate.sh: environment variables should follow the directory

Switching back and forth between several repositories is routine. One runs a certain major Node version, another runs a different one, and there’s also a Python service that needs a specific minor version plus a dedicated venv. I used to put a activate.sh in each repository root, and after switching over I’d source first. The problem is that “first”—most of the time I forget.

Forgetting doesn’t necessarily cause trouble on the spot. When running a local migration script, the script reads DATABASE_URL, while the shell still holds the value exported by the previous project, so the script connects to a different database and creates a few extra tables. No data was lost, but confirming it hadn’t affected anything else took a lot of time. After that I handed this whole thing over to direnv.

Looking back now, the problem with activate.sh isn’t that it’s sloppily written, but that it hangs the matter of “the environment being correct” on human memory. People will always forget, especially when three terminals, two editors, and one production troubleshooting session are all happening at once. It also has no concept of undo: source one and then source another, and it’s two layers stacked, with who overrode whom only guessable.

What it actually does is very little

direnv hooks into the shell. When you cd into a directory, it searches upward along the way for .envrc, and if it finds one it executes it, injecting the variables exported inside into the current shell; when you leave, it undoes them. No daemon, no config center, just this one action. What’s truly valuable is actually the second half—undoing on exit—which is something activate.sh never did.

After installing, hook in one line in the rc file:

BASH5 lines
1
2
3
4
5
# zsh
eval "$(direnv hook zsh)"

# bash
eval "$(direnv hook bash)"

.envrc itself is a bash script, which is where it’s handier than a .env file: you can write logic, use functions:

BASH6 lines
1
2
3
4
5
6
export DATABASE_URL=postgres://localhost:5432/app_dev
export AWS_PROFILE=personal
export KUBECONFIG="$PWD/kube/config"

PATH_add bin
PATH_add scripts

PATH_add handles relative paths and also deduplicates. What was added is automatically removed when you leave the directory, so it won’t pile up longer and longer in PATH—this is the main reason I gave up on hand-writing export PATH=$PWD/bin:$PATH. With that approach, after dozens of cds in a day, PATH grows so long that even direnv status doesn’t want to look at it. What’s more annoying is that it doesn’t error, it just gets slower and harder to trace; one day you find which python pointing at a strange path, and only then do you start suspecting this.

If your team is already using .env, there’s no need to migrate; one line of dotenv_if_exists .env.local is enough. watch_file is also commonly used—specify that when a certain file changes, reload, for example watch_file package-lock.json; dependencies changed, so the environment most likely should change too.

There’s also personal override. .envrc goes into git, and the differences on my machine go into .envrc.local: the main file writes source_env_if_exists .envrc.local, and the latter is added to .gitignore. This combination is much less trouble than having everyone edit the same file, especially for those “only my machine is different” things—whether Homebrew is installed in /opt/homebrew or /usr/local; this kind of difference shouldn’t appear in team-shared config.

What really saves trouble is identity that follows the repository

The most dangerous environment variables aren’t configuration, they’re identity: which database to connect to, which cloud account to use, which cluster to hit.

Configuration mistakes usually error on the spot; identity mistakes often succeed quietly. A common scenario: you think you’re running local verification, but you’re actually connected to another environment’s database, and every operation succeeds—until someone asks how a certain piece of data changed. This kind of problem leaves no conspicuous exception in the logs; it can only be caught by comparing after the fact.

I used to rely on my memory. kubectl config use-context switch over, open a new terminal and it’s back to default; AWS is more troublesome—several profile names look alike, and when AWS_PROFILE isn’t set it falls back to default, and which account default is, sometimes you only remember when you see the bill. Now kubeconfig is placed per repository (not in git), .envrc points to it, and cd-ing in gives you the right cluster. Credentials still come from ~/.aws and the system keychain; the repository only holds pointers, not fake keys.

For Python projects I use layout python3; direnv manages a venv under .direnv/ itself, activating on entering the directory and exiting on leaving—I can’t be bothered to change the prompt. Other languages have corresponding layouts in stdlib too, node, ruby and so on; I read the stdlib source directly for the specific behavior, which is clearer than the docs.

The allow step is design, not hassle

The first time you enter a directory with a .envrc, direnv refuses to execute, shows blocked, and asks you to direnv allow.

Many people find this step annoying; I did the first time too. But what it blocks is real: .envrc is essentially running arbitrary code in your interactive shell. Cloning a repository is equivalent to getting a script waiting to execute—the same category of risk as npm install running postinstall, only more direct and more hidden. postinstall is at least confined to node_modules; what .envrc gets is your entire shell, including your SSH agent and your cloud credentials.

allow is recorded by content hash; changing one character in .envrc requires re-confirming. My habit now is: for a cloned repository, cat .envrc first, then allow, the same as reading the scripts in package.json. For my own repositories, after editing, direnv allow. direnv status shows what the current directory has loaded and which files are being watched; when troubleshooting “why is the variable wrong here,” it’s much faster than env | grep.

Two pitfalls I haven’t gotten around

Slow. Running heavy work in .envrc—starting nix develop, running a dependency install once—stalls on entering the directory. direnv has caching and only recomputes when relevant files change, but the first time and after every change you still have to wait, and this wait happens exactly at the moment you least want to be interrupted: just cd-ed in, about to read code. I now move heavy work out, leaving only instant things like exports and PATH in .envrc. The line in my head is roughly two hundred milliseconds; beyond that magnitude, the hand typing ls feels something’s off before the eyes do.

It only governs interactive shells. Terminals opened in VS Code generally inherit (they go through the same hook), but processes launched by the GUI, scheduled tasks in launchd, and the IDE’s debugger don’t get it. For these I now explicitly source a copy in the script, not expecting direnv to cover it. The judgment method is plain: when something goes wrong, first look at who started that process, and whether its parent process went through your shell.

I don’t use direnv in CI either; I just read .env directly. How to share the same variable source between local and CI is something I haven’t fully solved. Right now I explicitly export them in the CI script, which means maintaining two copies and relying on review to keep them from drifting apart. There’s no conclusion here; for now I accept the redundancy, since it’s at least easier to trace than “CI quietly has a variable that local doesn’t.”

When it’s not worth installing

When there’s only one project and one environment, it’s a net addition of one more file to maintain and one more allow to remember. What direnv solves is the cost of context switching; if you don’t switch often, the benefit is close to zero.

If the team already runs the dev environment in containers or devcontainers, the gain is also small. The container already isolates the shell, so the kind of cross-contamination direnv is meant to solve basically doesn’t happen at the container boundary. It’s better suited to situations with “multiple repos, running directly on the host, and inconsistent language versions.”

My current criterion is pretty crude: if a project’s README has more than two lines of export, give it a .envrc; if it’s only one line, writing it in the README is enough.

Next time you look at your own project’s install instructions, count those lines of export.

About this Post

This post is written by Lu's Blog, licensed under CC BY-NC 4.0.

#Command Line #Development Environment #Workflows

Comments