direnv - per sub-directory tree environment variables


My development has been increasingly on OSX & Linux the past few months using things like AWS CLI, Serverless, Go and NodeJS.

One of the problems is environment variables, for dev environment setup and storage of secrets, my profile file quickly got quite messy.


In comes direnv which I've been using on Ubuntu and MacOS. It allows me to setup environment variables for subtrees in the directory structure on disc.



sudo apt-get install direnv

MacOS with Homebrew

brew install direnv

Hook it in to the shell

This depends on the shell you're using, check the direnv setup instructions if your not using bash

I added the following to my ~/bash_profile in MacOS

eval "$(direnv hook bash)"

Per Sub-directory

Create a file called .envrc in the directory you want the environment variable to be available (and to all subdirectories). Your standard export directives go here.
Note that if you're not using bash, use bash syntax for this file, direnv won't work otherwise.

An example content is

export AWS_ACCESS_KEY_ID=blahblah
export AWS_SECRET_ACCESS_KEY=blahblahblah

That's it. It doesn't slow you down and does tell what environment variables are loaded and unloaded as you traverse the directory structure via the shell.