Bash – Set environment variables from file of key/value pairs


TL;DR: How do I export a set of key/value pairs from a text file into the shell environment?

For the record, below is the original version of the question, with examples.

I'm writing a script in bash which parses files with 3 variables in a certain folder, this is one of them:

MINIENTREGA_FICHEROS="informe.txt programa.c"

This file is stored in ./conf/prac1

My script then parses the file using this code:

cat ./conf/$1 | while read line; do
    export $line

But when I execute prac1 in the command line it doesn't set the environment variables

I also tried using source ./conf/$1 but the same problem still applies

Maybe there is some other way to do this, I just need to use the environment variables of the file I pass as the argument of my script.

Best Solution

This might be helpful:

export $(cat .env | xargs) && rails c

Reason why I use this is if I want to test .env stuff in my rails console.

gabrielf came up with a good way to keep the variables local. This solves the potential problem when going from project to project.

env $(cat .env | xargs) rails

I've tested this with bash 3.2.51(1)-release


To ignore lines that start with #, use this (thanks to Pete's comment):

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

And if you want to unset all of the variables defined in the file, use this:

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


To also handle values with spaces, use:

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

on GNU systems -- or:

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

on BSD systems.

From this answer you can auto-detect the OS with this:


## Usage:
##   . ./ ; $COMMAND

if [ "$unamestr" = 'Linux' ]; then

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

elif [ "$unamestr" = 'FreeBSD' ]; then

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