Environment Variables – Set Directory/Project Local Variables

bashenvironment-variablesshellzsh

I have been working on several projects, and they require different environment variables (e.g., PATH for different versions of clang executables, PYTHONPATH for several external modules). Whenever I work on one project, I have to modify these environment variables myself (e.g., change .zshrc/.bashrc and source it); and I sometimes forget and make mistakes.

Is there a way/project that helps do this automatically, similar to what virtualenv does in Python?

Best Answer

There're mature tools designed to set environment variables for a specific directory.

Compared with other tools designed for this, direnv is the best of them. One of the main benefit is that it supports unloading the environment variables when you exit from that directory.

direnv is an environment switcher for the shell. It knows how to hook into bash, zsh, tcsh, fish shell and elvish to load or unload environment variables depending on the current directory. This allows project-specific environment variables without cluttering the ~/.profile file.

What makes direnv distinct between other similar tools:

  • direnv is written in Go, faster compared with its counterpart written in Python
  • direnv supports unloading environment variables when you quit from the specific dir
  • direnv covers many shells

Similar projects

  • Environment Modules - one of the oldest (in a good way) environment-loading systems
  • autoenv - lightweight; doesn't support unloads; slow written in Python
  • zsh-autoenv - a feature-rich mixture of autoenv and smartcd: enter/leave events, nesting, stashing (Zsh-only).
  • asdf - a pure bash solution that has a plugin system
Related Question