Using direnv to Manage Environment Variables

Learn how to use direnv to manage environment variables.

We'll cover the following

Setting up direnv

If you have experience with software development, you’re probably used to juggling a few different API keys for things. Perhaps your application uses a token to keep cookies secure or an API token for managing cloud servers. Many applications push developers to place these tokens in environment variables, but this can clog up our .bashrc files.

The direnv program lets us keep environment variables with our project. When we enter the directory, direnv sets the environment variables we need. When we leave the directory, those variables are removed.

We install direnv with the package manager. On Ubuntu, we use this command:

sudo apt install direnv

On macOS, we use the following:

brew install direnv

This installs direnv, but we also need to activate it by adding some code to our .bashrc file:

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

The direnv hook bash command hooks the direnv into our shell. Using eval executes arguments as a shell command. Use the terminal below to practice this command.

Get hands-on with 1400+ tech skills courses.