When I am working on multiple projects for multiple organisations I find myself altering environment variables on the machines I am working on to help me do my job. This up until recently has been a manual process and I often tell people how I’m lazy so look for ways to be more efficient.

I can’t remember who introduced me to a cool little utility called direnv, all I remember is I saw it in one of the internal Slack channels. So what does it do?

The purpose of direnv is to make it easier to switch environment variables depending on what (or where) I am working on. It allows project specific variables to be set in a specific directory. This saves me messing about with ~/.profile settings or unset, exporting variables.

When you change into a directory direnv checks for the existence of a .envrc file, should it exist it is loaded into a bash sub-shell and all exported variable are made available to . the current shell. Leaving the directory will also unset the variables.

More information can be found here or the GitHub Repo. It was nice and easy to install with homebrew, however it took me a few minutes to realise that I needed to update my .zshrc with a simple line (check the instructions if you use Bash, Fish etc.).

eval "$(direnv hook zsh)"

An example of how it works is (lifted straight from their website);

$ cd ~/my_project
$ echo ${FOO-nope}
nope
$ echo export FOO=foo > .envrc
.envrc is not allowed
$ direnv allow .
direnv: reloading
direnv: loading .envrc
direnv export: +FOO
$ echo ${FOO-nope}
foo
$ cd ..
direnv: unloading
direnv export: ~PATH
$ echo ${FOO-nope}
nope

I am still getting used to it and have high hopes that it will be useful ….. time will tell.