Set environment variables from file

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

MINIENTREGA_FECHALIMITE="2011-03-31"
MINIENTREGA_FICHEROS="informe.txt programa.c"
MINIENTREGA_DESTINO="./destino/entrega-prac1"

This file is stored in ./conf/prac1

My script minientrega.sh then parses the file using this code:

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

But when I execute minientrega.sh 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.


Problem with your approach is the export in the while loop is happening in a sub shell, and those variable will not be available in current shell (parent shell of while loop).

Add export command in the file itself:

export MINIENTREGA_FECHALIMITE="2011-03-31"
export MINIENTREGA_FICHEROS="informe.txt programa.c"
export MINIENTREGA_DESTINO="./destino/entrega-prac1"

Then you need to source in the file in current shell using:

. ./conf/prac1

OR

source ./conf/prac1

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 $(cat .env | grep -v ^# | xargs)

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

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

-o allexport enables all following variable definitions to be exported. +o allexport disables this feature.

set -o allexport
source conf-file
set +o allexport
链接地址: http://www.djcxy.com/p/24148.html

上一篇: 在网格布局上进行手势检测

下一篇: 从文件设置环境变量