How to automatically set environment variables per folder (directory) on bash shell on macOS High Sierra

I have a little CLI toy project that uses the file system for storage (YAML files) and defaults to a dot folder under the home folder (~), this default can be overridden by an environment variable that sets the path. To ease manual testing, I wanted to automatically set up an environment variable wheneve I cd’ed into the project folder, also as bonus I wanted this variable to be removed from the environment whenever I cd’ed  out.

Googling a bit, I found Autoenv: Directory-based Environment, from Kenneth Reitz, this project is archived and nicely provides a pointer to direnv — Unclutter your .profile which actually works with any *nix and most common shells in use including bash and zshell .

In the case of macOS you just need to install it via brew  like:

$ brew install direnv

And hook it into your shell. The instructions for bash asked to add:

eval "$(direnv hook bash)"

To ~/.bashrc  “after rvm, git-prompt and other shell extensions that manipulate the prompt.”  which didn’t work for me. In my case, my prompt and such stuff is in .bash_profile  So I placed it at the bottom of this file reloaded the shell and it started working.

Just follow the instruction on, and now you will be able to set up environment variables for your shell that apply only to specific folders, and all of this in an automated and convenient fashion.

Leave a reply:

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Site Footer