Import environment variables from file in shell scripts

This might be helpful:

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

Or keep the variables local. This solves the potential problem when going from project to project.

env $(cat .env | xargs) rails

To ignore lines that start with #, use this:

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.