Load a project variable with direnv
Set up a direnv shell hook, inspect and allow a small .envrc, and watch a project variable disappear when you leave.
Updated
in short
direnv loads environment changes from an allowed .envrc when you enter a directory and unloads them when you leave.
Use the small fixture below to check the workflow before applying it to your own project.
Tools used
Before you start
- A Bash or Zsh terminal on Linux or macOS
- The listed tools installed and available on PATH
Steps
Step 1: Enable your shell hook
For Bash, add this line once at the end of ~/.bashrc, then open a new terminal. For Zsh, use direnv hook zsh in ~/.zshrc instead.
sheval "$(direnv hook bash)"Step 2: Create and inspect the project file
The variable is harmless. Read an .envrc before allowing it: it is executable shell code.
shtrmn_guide_dir="$(mktemp -d)" cd "$trmn_guide_dir" printf '%s\n' 'export TRMN_GUIDE_COLOR=green' > .envrc cat .envrcoutputexport TRMN_GUIDE_COLOR=green
Step 3: Allow and inspect it
Run each line at a separate prompt so the hook can update your environment.
shdirenv allow . printf "%s\n" "$TRMN_GUIDE_COLOR"Step 4: Leave the project
Again, wait for the next prompt before printing the variable.
shcd .. printf "%s\n" "${TRMN_GUIDE_COLOR-unset}"
Further reading
[direnv shell hooks](https://direnv.net/docs/hook.html) · [direnv documentation](https://direnv.net/)
FAQ
- Why is my variable still empty?
- The shell hook updates the environment at prompt boundaries. Reopen your shell after installing the hook and execute the example one line at a time.
- What happens when .envrc changes?
- Review the changed file, then allow it again. Do not approve an unfamiliar file just to silence the warning.