function lenv {
path=$PWD
while [[ ! -f "$path/.env" && "$path" != '/' ]]; do
path=$(dirname "$path")
done
if [ -f "$path/.env" ]; then
source "$path/.env"
fi
}
function cd { builtin cd "${@}"; lenv; }It lacks the security but it works recursively and allows more than just environment variables. A common script I have is to automatically build for instance:
here=$(dirname ${BASH_SOURCE[0]})
function autobuild {
(
mkdir -p build
cd $here/build
../configure
while true; do
make && make check
inotifywait -qr -e close_write,delete $here/src $here/test $here/Makefile.am
done
)
}
I've tried generalizing the latter but between different targets, different build systems, different projects structures etc, copy and pasting something like this per project is the least worst option.If there is no .envrc in the directory it will look for one in the parent directory, but it won't activate more than one.
Also one thing it does that your hand-rolled version does not is that it remembers what the environment variables were before and restores them to that state when you exit the directory.
My above example wasn't running the command, just defining it to be run manually. The .env becomes a dumping ground for all sorts of project specific stuff. The docs say direnv doesn't support this.
> Also one thing it does that your hand-rolled version does not is that it remembers what the environment variables were before and restores them to that state when you exit the directory.
I've thought of adding this, but apart from a couple of things I reset manually I haven't really found the need.
I figure you can also use it in conjunction with `module load` to automatically load the right module when you enter a project's directory. Modules are used in many computing clusters to manage environments.
Also direnv will never execute an .envrc without permission, you need to run `direnv allow` whenever there is a new or newly modified .envrc.