Dev tools and workflow · Beginner · 14 min
Load project environment variables automatically with direnv
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · direnv 2.38.2 (official release binary)
You will install direnv 2.38, hook it into bash or zsh and give a demo project its own environment that loads when you enter the folder and unloads when you leave, with a .env file, a Python virtual environment, shared parent settings and an untracked secrets file.
On this page
Most projects need a few environment variables before anything works: which mode to run in, a port, a database address, an API key. People keep them in a README, paste export lines into every new terminal, or forget and spend ten minutes on a confusing error.
direnv fixes this at the shell level. You put a file called .envrc in the project folder. When you cd into the folder, direnv runs it and adds its variables to your shell; when you cd out, it takes them away again. It works for any language, because all it changes is the environment your commands start in.
You will build this up in a throwaway project, ~/direnv-demo/api, one feature per step. The commands work on Ubuntu 26.04, and on macOS except where a step says otherwise.
Step 1 · Install direnv 2.38
direnv is a single binary. Ubuntu's archive has a direnv package, but it can lag behind the upstream release (apt-cache policy direnv shows which version it offers). This installs the official 2.38.2 build from GitHub instead and checks it against the SHA256 digest published on the release page. It picks the build for your processor from uname -m.
sudo apt update
sudo apt install -y curl ca-certificates
cd "$(mktemp -d)"
case "$(uname -m)" in
x86_64) ASSET=direnv.linux-amd64; SUM=148820a187930d36ca6a204504e5cdb30d8396cd1a97e64c3b3f10d793c11247 ;;
aarch64) ASSET=direnv.linux-arm64; SUM=ec2a32dbe2f19dd085bd9315a1b4ea88b55ec288aa7eabe8723490baf466cb23 ;;
*) echo "No build listed here for $(uname -m); see the releases page"; false ;;
esac
curl -fsSLO "https://github.com/direnv/direnv/releases/download/v2.38.2/${ASSET}"
echo "${SUM} ${ASSET}" | sha256sum --check
sudo install -m 755 "${ASSET}" /usr/local/bin/direnvsha256sum prints the file name followed by OK. If it prints FAILED, delete the download and try again; do not install a binary that fails the check.
A binary installed by hand gets no updates from apt. To upgrade, take the new version's digests from the releases page and run the same commands with the new file names. On macOS, brew install direnv installs the current release and Homebrew keeps it updated.
The download is about 8 MB. If you pay for data by the bundle, fetch it once and copy the same file to other Linux machines with the same processor type.
Check it worked
direnv versionThe output is 2.38.2.
Step 2 · Hook direnv into your shell
direnv does nothing until your shell asks it to. The hook is a small function that runs before every prompt: it asks direnv whether the folder you are in has an environment to load or unload, and applies the answer.
For bash, add the hook to the end of ~/.bashrc:
echo 'eval "$(direnv hook bash)"' >> ~/.bashrcFor zsh (the default on macOS), add it to ~/.zshrc instead:
echo 'eval "$(direnv hook zsh)"' >> ~/.zshrcPut the line after anything else in the file that changes your prompt, such as a prompt theme, so direnv's function is not overwritten. Then open a new terminal so the file is read again.
Check it worked
In the new terminal, run type _direnv_hook in bash, or whence -f _direnv_hook in zsh. Both print the body of a function called _direnv_hook. If the shell says the name is not found, the hook line is missing from the file your shell reads, or you are still in the old terminal.
Step 3 · Write a first .envrc and allow it
Create the project with a small script in bin/ that reports its settings:
mkdir -p ~/direnv-demo/api/bin
cd ~/direnv-demo/api
cat > bin/orders-info <<'EOF'
#!/bin/sh
echo "${APP_NAME:-unknown} (${APP_ENV:-no env}) on port ${PORT:-unset}"
EOF
chmod +x bin/orders-infoNow write the .envrc. It is a bash script, so plain export lines work. PATH_add is a direnv helper that puts a folder at the front of PATH as an absolute path, so you can run the project's own scripts by name:
cat > .envrc <<'EOF'
export APP_NAME=orders-api
export APP_ENV=development
export PORT=8040
PATH_add bin
EOFWith the hook in place, direnv notices the new file at your next prompt and refuses to load it, printing something like:
direnv: error /home/you/direnv-demo/api/.envrc is blocked. Run `direnv allow` to approve its contentThat is on purpose. An .envrc can run any command with your permissions, and it runs as soon as you cd into a folder. Without this check, cloning a repository and looking inside it would be enough to run someone else's code. direnv only loads a file you have approved, and the approval is tied to the file's path and exact content.
Read the file, then approve it:
direnv allowThe shell prints something like direnv: loading ~/direnv-demo/api/.envrc and then direnv: export +APP_ENV +APP_NAME +PORT ~PATH: a plus for each new variable and a tilde for each changed one.
Check it worked
In your hooked shell, run the script by name:
orders-infoThe output is orders-api (development) on port 8040. Scripts, cron jobs and CI have no prompt for the hook to run on. direnv exec <folder> <command> loads the folder's environment and runs one command in it, which gives the same result without the hook:
direnv exec ~/direnv-demo/api orders-infoStep 4 · See why direnv asks again after every change
Add a line to the .envrc:
echo 'export FEATURE_FLAGS=new-checkout' >> .envrcAt the next prompt direnv shows the blocked message again, because the content no longer matches what you approved. This also catches a git pull that quietly changes the file: you get a chance to read the change before it runs. Look at what changed (cat .envrc, or git diff .envrc in a real repository), then approve it again:
direnv allowTo switch a project's .envrc off without deleting it, run direnv deny in the folder. It stays blocked until you allow it again.
Check it worked
direnv exec . sh -c 'echo "$FEATURE_FLAGS"'The output is new-checkout. If you see the blocked error instead, run direnv allow in ~/direnv-demo/api again.
Step 5 · Load a .env file with dotenv
Many tools (Docker Compose, a lot of web frameworks) already read settings from a .env file of plain KEY=value lines. direnv's dotenv helper loads the same file into your shell, so command-line tools see what the app sees and you keep one copy of each value. direnv parses the file itself; it does not run it as shell code.
cat > .env <<'EOF'
DATABASE_URL=postgres://orders@localhost:5432/orders_dev
DEFAULT_CURRENCY=KES
EOF
echo 'dotenv' >> .envrc
direnv allowdotenv with no argument reads .env in the same folder, and prints an error if the file is missing (the rest of .envrc still loads unless you have turned on strict_env). If some team members do not have one, use dotenv_if_exists instead. direnv also watches the file, so an edit to .env reloads the environment at your next prompt without another direnv allow.
Check it worked
direnv exec . sh -c 'echo "$DATABASE_URL $DEFAULT_CURRENCY"'The output is postgres://orders@localhost:5432/orders_dev KES.
Step 6 · Activate a Python virtual environment automatically
layout python3 creates a virtual environment the first time the .envrc loads, and activates it every time you enter the folder. It sets VIRTUAL_ENV and puts the environment's bin/ at the front of PATH, so python and pip are the project's own. There is no source .venv/bin/activate to forget, and no deactivate when you leave.
On Ubuntu, python3 -m venv needs the python3-venv package:
sudo apt install -y python3 python3-venv
echo 'layout python3' >> .envrc
direnv allowThe environment lives in .direnv/python-3.X/ inside the project, named after your Python's minor version. Creating it needs no download; packages you later pip install go into it and stay out of your system Python. On a metered connection, install a project's packages once and reuse the same folder rather than recreating it.
Check it worked
direnv exec . sh -c 'command -v python; echo "$VIRTUAL_ENV"'Both lines point inside ~/direnv-demo/api/.direnv/python-3.X, for example /home/you/direnv-demo/api/.direnv/python-3.14/bin/python (your minor version may differ). Outside the folder, command -v python on Ubuntu usually prints nothing, because Ubuntu only ships python3 unless you have installed python-is-python3.
Step 7 · Share settings from a parent folder with source_up
When several projects sit in one folder, such as a company workspace, some settings are the same for all of them. Put those in an .envrc in the parent folder:
cat > ~/direnv-demo/.envrc <<'EOF'
export TEAM=payments
export LOG_LEVEL=info
EOF
cd ~/direnv-demo
direnv allow
cd ~/direnv-demo/apidirenv only loads the nearest .envrc, so inside api/ the parent file is ignored until the project asks for it. source_up finds the next .envrc above the current folder and runs it. Put it first, so the project's own lines can override what it sets. Rewrite the project's .envrc with source_up at the top and a project-specific log level:
cat > .envrc <<'EOF'
source_up
export APP_NAME=orders-api
export APP_ENV=development
export PORT=8040
export FEATURE_FLAGS=new-checkout
export LOG_LEVEL=debug
PATH_add bin
dotenv
layout python3
EOF
direnv allowA file pulled in by source_up is not checked by direnv allow. Approving api/.envrc means trusting whatever the parent .envrc contains, so only use source_up under folders you control.
Check it worked
direnv exec ~/direnv-demo/api sh -c 'echo "$TEAM $LOG_LEVEL"'
direnv exec ~/direnv-demo sh -c 'echo "$TEAM $LOG_LEVEL"'The first line is payments debug: the team comes from the parent and the project overrides the log level. The second is payments info, the parent's own settings.
Step 8 · Keep secrets in an untracked .envrc.local
The .envrc is worth committing, so everyone on the team gets the same setup. Secrets do not belong in it. Keep each developer's keys in a second file, .envrc.local, that never leaves their machine, and have .envrc load it if it exists:
echo 'source_env_if_exists .envrc.local' >> .envrc
direnv allowCreate the file with owner-only permissions before anything goes into it:
install -m 600 /dev/null .envrc.localThen add the key without it appearing on screen or in your shell history. read -s reads without echoing, and printf %q quotes the value safely for the file. The prompt is printed separately because read -p means something different in zsh, so this form works in both bash and zsh:
printf 'Payments API key: '; read -rs key; echo
printf 'export PAYMENTS_API_KEY=%q\n' "$key" >> .envrc.local
unset keyLike .env, .envrc.local is watched, so edits reload without another allow, and it is not checked by direnv allow either: it is your own file. Now keep the private files out of git. .env often ends up holding passwords too, so treat it as private and commit an .env.example with dummy values if the team needs a template. .direnv/ holds the virtual environment, which does not belong in a repository either. On Ubuntu the first line installs git; on macOS skip it, as git comes with the Xcode command line tools (xcode-select --install) or brew install git:
sudo apt install -y git
cat > .gitignore <<'EOF'
.env
.envrc.local
.direnv/
EOF
git init -q
git status --short --untracked-files=allVariables in your shell are passed to every program you start from it, so anything run in this folder can read the key. Load only the secrets the project needs, and see Keep secrets out of git for what to do if one is committed by mistake.
Check it worked
git status lists .envrc, .gitignore and bin/orders-info, and nothing else: no .env, no .envrc.local, nothing under .direnv/.
ls -l .envrc.local
direnv exec . sh -c 'test -n "$PAYMENTS_API_KEY" && echo "key loaded"'ls -l starts with -rw-------: only you can read the file. The second command prints key loaded without printing the key itself.
Step 9 · Leave the folder and watch everything unload
In your hooked shell, move out of the project:
cd ~direnv prints direnv: unloading and puts back the environment you had before you entered: the project variables are gone, the virtual environment is no longer active and PATH loses bin/ and .direnv/python-3.X/bin. A variable the project changed, rather than added, gets its old value back. cd ~/direnv-demo/api loads it all again, without asking, because nothing has changed since you allowed it.
Check it worked
After cd ~, the first line prints unset, and command -v prints nothing at all:
echo "${APP_NAME:-unset}"
command -v orders-infoWhen you have finished, delete the demo. direnv keeps a record of each file you allowed in ~/.local/share/direnv/allow/; direnv prune removes the records for files that no longer exist:
cd ~
rm -rf ~/direnv-demo
direnv pruneKeep /usr/local/bin/direnv and the hook line if you will use direnv; otherwise remove the line from ~/.bashrc or ~/.zshrc and run sudo rm /usr/local/bin/direnv.
Next steps
- Make sure a key never reaches a repository with Keep secrets out of git.
- Give the project named commands that use these variables with just, a command runner.
- Lint the Python code in your new virtual environment with Ruff.
Related tutorials
- Work on two branches at once with git worktreeYou will fix an urgent bug in a second working tree without stashing your half-finished feature, merge the fix, and clean up every extra tree afterwards.
- Version releases with semantic versioning, Git tags and a changelogYou will take a small shell library from 1.0.0 to 1.1.0 with written version rules, Conventional Commits, a Keep a Changelog file, annotated Git tags, a build stamped by git describe and release notes drafted from the commits since the last tag.
- Search files and shell history interactively with fzfYou will have fzf 0.75 wired into your shell for history search, file insertion and directory jumps, fed by fd with a preview pane, plus two small pickers that switch Git branches and stop processes.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials