Skip to main content

Sudarsan's Blog

Env variables

Ever wake up on the symmetrical side of the bed? Like at the middle? Yep. That�s when you decide that you are never going to (ever) code in constants in your application. So how do you get them? Configuration files? JSONs? Yamls? Environment variables are more elegant and easier with a docker-compose no?

12 factor apps are what cool kids are doing these days (read three years ago). And it makes sense that you put your configurable variables into the environment and do a getenv. But what happens when you have twelve twelve factor apps with twelve different sets of environment configurations?

If you put these into a script/environmental file like below and source them, then you probably have the right idea.

    export CONSTANT_1 = stuff
    export CONSTANT_2 = morestuff
    export CONSTANT_3 = youguesseditmorestuff

But why not harness the incredible power of zsh and chpwd? The gist is, chpwd is a hook that fires everytime your (yep) pwd changes. Just make sure your constant settings (like above) go into a variable.env file and source it at chpwd. Just put this in your .zshrc.

function chpwd(){
    if [ -r $PWD/<environmentvariablefilename.env> ] ; then
        source $PWD/<environmentvariablefilename.env>
    fi
}

So, if there’s a file to be sourced, we source it. Saved me a couple of seconds. Have fun.