Gatlin.io Icon
Image of Austin Gatlin's face
February 28, 2022 (last updated March 10, 2022)

Direnv

Direnv is a utility that loads/unloads env vars depending on your directory. It does this via an .envrc file filled with directory-specific env vars that you want in your global env. When you leave that directory, direnv removes those same env vars. This keeps your global env minimal and clean.

Install

After installing direnv, activate the appropriate hook based on your shell.

Understanding the hook

As an example, the setup instructions for bash ask you to write the following in your ~/.bashrc:

eval "$(direnv hook bash)"
  • direnv hook bash will generate a direnv-specific shell script. You can run it in isolation to see what it outputs. The script seems to essentially be a wrapper around the internal export command.

  • "$(direnv hook bash)" will turn the script into a string.

  • eval "$(direnv hook bash)" evaluates the script-string in place. This is equivalent to writing the functions by hand into your ~/.bashrc file. (Don't actually write the script manually, for the record. Let direnv control itself.)

Older docs instructed you to run the following command:

echo 'eval "$(direnv hook bash)"' >> ~/.bashrc

This is equivalent to manually writing eval "$(direnv hook bash)" in ~/.bashrc.