Direnv env dir
Supports use_env_dir
function, which loads environment variables one per file under the .direnv/env
directory.
Add the following into your .config/direnv/direnvrc
:
# Usage: use_env_dir [env_dir]
#
# Load environment variables from `$(direnv_layout_dir)/envs" directory.
# Under this directory, every file is read and set to an environment
# variable whose name is the filename and value is the file content.
#
# Also watch files so to automatially reload on every file update.
use_env_dir() {
local env_dir
env_dir="${1:-$(direnv_layout_dir)/envs}"
if [[ -d $env_dir ]]; then
for f in "$env_dir"/*; do
if [[ -f $f ]]; then
watch_file "$f"
export "$(basename "$f")=$(cat "$f")"
fi
done
fi
}
This function gives you an ability which is similar to the one in Heroku Buildpack.
Each file under the "env_dir" represents an environment variable, whose filename to be the variable's name and content to variable's value.
For example, a file with the name of DB_PORT
and the content 32800
will be an environment variable of DB_PORT=32800
.
In .envrc
, put the following line:
use_env_dir
You can also specify the env dir as:
use_env_dir /path/to/your/env/dir
When you launch a database server container by docker-compose
, you can let it to pick any available port and put the port into DB_PORT
.
$ mkdir -p .direnv/envs
$ docker-compose port db 5432 | cut -d ':' -f 2 > .direnv/envs/DB_PORT
And make your application to read the DB_PORT
.
In this way, you can access the db without worrying about port conflict, no matter how many similar projects you are working on in parallel.