direnv

Shell extension that automatically loads/unloads environment variables when entering/leaving a directory. Uses .envrc files. Hooks into bash, zsh, fish, tcsh, and elvish.

Workflow

echo 'export API_KEY=abc123' > .envrc
direnv allow          # must explicitly allow new/changed .envrc
cd ..                 # env vars are unloaded automatically
cd project/           # env vars are loaded again

Shell setup

# fish
echo 'direnv hook fish | source' >> ~/.config/fish/config.fish
 
# bash
echo 'eval "$(direnv hook bash)"' >> ~/.bashrc
 
# zsh
echo 'eval "$(direnv hook zsh)"' >> ~/.zshrc

Key commands

CommandEffect
direnv allowTrust the current .envrc
direnv denyBlock the current .envrc
direnv reloadRe-evaluate .envrc without leaving directory
direnv editOpen .envrc in $EDITOR and auto-allow on save
direnv statusShow current state
direnv exec /path cmdRun command in the env of a given directory

NixOS / Home Manager

programs.direnv = {
  enable = true;
  nix-direnv.enable = true;  # faster nix integration with caching
};