I use a lot of different tools to automate steps and make my life easier when developing apps or working on my laptop in general. One of those tools is direnv
It’s a neat little tool written in golang that hooks into your shell and sets up environment variables from a file. Similar to how dotenv works, except it can do much more interesting things, like calling shell commands. It also automatically loads and unloads settings as you change directories in your shell. It looks for a file called .envrc
in the folder and if it has been added to the allow list it will run through the commands there and merge it into the running shell.
A basic way I use it is to set up configuration variables for the application I’m working on and check those into git so everyone has a basic setup going. Then I add a file I call .env.local
that is added to .gitignore
where I keep env variables that are specific to me or my environment.
I’ve worked in quite a few teams that had a load of different .env files shared in different ways, it’s a chore to make sure they are kept up to date and ensure they are not accidentally commited to source. I think direnv manages to find a good balance here, allowing a nice pattern where a default configuration set is committed to source, while also allowing personal settings to be applied easily.
Simple Example
|
|
|
|
This will load the .envrc file and all the shell commands will run, the environment variable FOO
will be set to ‘bar’. Then it loads the .env.local
file and applies any overrides, setting FOO
to ‘rab’ and also setting BAR
to ‘OOF’
direnv is available for most shells and linux based platforms, check the installation guide for details on setting it up for your environment.