There are a lot of duplicate questions about setting permanent environment variables, but no questions about setting them for a specific folder.
So, how to set an environment variable for a specific folder?
Clearifying: I want my CUSTOM_ENV_VAR
to activate only when i work in a specific dir .../custom_dir/
. So when i launch programs in the folder, programs use this CUSTOM_ENV_VAR
, when i launch outside – programs do not use it.
Best Answer
Using
direnv
Install
direnv
, which is a tool for this purpose which is a statically linked executable that hooks into your shell (csh,bash, and the like)Now to whichever folder you'd like the environment variables to be set, add an
.direnvrc
file that must have valid bash syntax. For example of your case, you can load both pyenv's version management as well as your own variables by setting your.direnvrc
to:You can see other examples at their wiki
Thanks to @ChrisKuehl in the comments for the suggestion
Another alternate approach would be to override the
PROMPT_COMMAND
(as suggested in the comments by @steeldriver) to point to a function that loads your environment variable up, by adding something like this to your.bashrc
Now when you enter
yourdirectorypath
, it'll automatically setCUSTOM_ENV_VAR
, when you exit out of it, it'llunset
(remove) the variable, hence that variable is only available when the current directory isyourdirectorypath