Today I Learned

Set, Export, and Unset Environment Variables from a File in Bash

When working with software applications, it’s common to need a manageable way to store configuration information.Environment variables provide an excellent solution, allowing us to keep sensitive credentials, system configurations, or other settings separate from our application codebase. But how would you go about managing these variables in a streamlined manner? The answer lies in the power of the Unix or Linux bash shell. Today, I want to share a quick tip for how you can set environment variables from a file of key/value pairs.

Let’s take a look at the following bash command:

env $(cat .env | xargs) my_command

In the above command, $(cat .env | xargs) will read the key/value pairs from the .env file and pass them as arguments to the env command. The env command subsequently sets these variables and executes my_command.

The .env file typically contains one key/value pair per line (e.g., DB_USER=myuser and DB_PASSWORD=mypassword). The cat command reads this file, and xargs converts the contents into a single string that env can work with.

What if your .env file contains comments or other non-variable lines starting with #? In such cases, you’d want to ignore these lines. You can accomplish this with the grep -v '^#' command. The grep -v '^#' statement filters out lines starting with the # character. The adjusted command then becomes:

export $(grep -v '^#' .env | xargs)

Finally, knowing how to set these variables is only half the job; there will be situations where you need to unset or clear all variables defined in your .env file. The following command does exactly that:

unset $(grep -v '^#' .env | sed -E 's/(.*)=.*/\1/' | xargs)

In this command, $(grep -v '^#' .env | sed -E 's/(.*)=.*/\1/' | xargs) is used again to filter out lines starting with #, extract the variable names (everything before the = sign), and convert them into a single-line string. The unset command then uses this output to unset each of these environment variables.