Linux: Bash: read environment vars from file for script security


Example

.env

$login_name=me

$login_pass=secret

Script

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

echo $login_name

me

echo $login_pass

secret

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

Update:

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)

Update:

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.

--Silas Paul

Tags