Custom *per directory* Environment Variables

Ovid on 2008-06-05T14:59:13

It's a long story why I needed this, but I did. First, we create a little Perl program which can read a YAML file (it's simple now, but might get extended in the future).

#!/usr/bin/perl

use YAML::Tiny 'LoadFile';

exit unless -e '.dev';
my $yaml = LoadFile('.dev');

my $env = $yaml->{env} || {};
while ( my ( $var, $value ) = each %$env ) {
    # make it easy for the shell to parse
    print "$var\t$value\n";
}

The YAML file might look something like this:

---
env:
    TEST_DB: some_db
    TEST_USER: some_user
    TEST_PASS: some_pass

And then in a bash script named "script/env_setup.sh":

#!/usr/bin/bash

while read env_var value; do
    export $env_var="$value"
done < <(perl -Ideps/lib/perl5 script/env_setup.pl)

And the coup-de-grace, in your .bash_profile:

function cd {
    builtin cd "${@}"

    if [ -f ./script/env_setup.sh ]; then
        source ./script/env_setup.sh
    fi
}

Please don't tell anyone I told you.


don't forget...

phillup on 2008-06-05T17:03:47

Don't forget the other ways to change a directory, like pushd and popd.

Also, I'd recommend an echo statement if the env was changed so you don't forget that it is happening.

Might help in the future if you have an env related bug and forgot about this...

And, thanks for the hint. I've been opening multiple terminals and setting up my "environment" for some items that I work on. May change based on this, since those changes are highly correlated to the directory structure I use for projects.

Re:don't forget...

Ovid on 2008-06-05T17:32:32

I deliberately left pushd and popd out because our env_setup actually does a heck of a lot more (like build separate test databases for each branch) and I use those for "alternate" navigation (though I know I can just do "builtin cd" :).

The echo statement is a great idea, though. Thanks.

Another wrinkle to consider ...

drhyde on 2008-06-09T13:35:10

You probably want to have 'cd' also undo those environment changes when you change out of a directory that has that magic file in it. That's important if you're using this to do things like mess around with $PATH or $LD_LIBRARY_PATH.

Nice trick though.

Recently solved the same problem

cxreg on 2009-04-23T21:12:10

I just wrote a handful of bash functions to scratch this same itch, which also include some handy bash array functions and drhyde's suggestion of unsetting on exit.

If you're interested, this code is at http://github.com/cxreg/cxregs-bash-tools

Re:Recently solved the same problem

Ovid on 2009-04-23T22:06:06

Thanks. That looks useful.