DotEnv

Many times, I am working on a project and I am running into problems because one of two things has happened: 1) I forgot to source my environment variables, 2) I forgot I had environment variables sourced.

These two issues are common and can be very dangerous! Imagine running a terraform apply on the wrong project, with the wrong settings, or making an API call to a service which you thought was dev but ended up being prod.

To help with this, dotenv will automatically source .env when changing directories. The best part about it is, it will also unset your variable when you leave the directory! This of this as auto garbage collection.

Looking at the Code

In order to achieve this, there are a few considerations to keep in mind.

First, we want it to work under by long-hand and short-hand directory traversal. This means when we use cd .. vs .., our solution should work under both cases.

It has nothing to do with being lazy or ignorance; it has everything to do with magic being magic because something unexpected happened.

Next, we want to consider feedback when something is set. The worst experience in my opinion is that many scripts do things behind the scenes and you might not catch it. It has nothing to do with being lazy or ignorance; it has everything to do with magic being magic because something unexpected happened.

We will override the cd function, and call builtin cd which is a great way to reference the zsh or bash built-in cd function. Remember, it’s almost always better to us a function vs an alias since you get more control over what happens.

When changing a directory, before we excecute the cd command, we check for the .env file. If we find it, we will check it for the environment variable names. We will unset them if the file is found.

Next, we are going to change the directory.

Immediately following the changing of the directory, we check again for the existence of .env in the new directory. If it’s found, we will source it with the help of allexport which will auto-export the variables to make sure your child processes can access them.

Compatibility with ZSH’s AutoCD

I noticed in testing that there was compatibility issues with zsh’s setopt autocd. Technically, it does not use the underlying cd command, which will cause a conflict above. To get the same (relative) behavior, you can use something like the above, where we overload the “..” functions.

Share this post