从键/值对文件中设置环境变量 [英] Set environment variables from file of key/value pairs

查看:79
本文介绍了从键/值对文件中设置环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TL; DR:如何将一组键/值对从文本文件导出到Shell环境中?

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.

我正在用bash编写一个脚本,该脚本分析某个文件夹中具有3个变量的文件,这是其中之一:

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"

此文件存储在./conf/prac1

This file is stored in ./conf/prac1

然后,我的脚本minientrega.sh使用以下代码解析文件:

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

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

但是当我在命令行中执行minientrega.sh prac1时,它没有设置环境变量

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

我也尝试使用source ./conf/$1,但仍然存在相同的问题

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.

推荐答案

您的方法存在的问题是while循环中的export发生在子外壳程序中,并且这些变量在当前外壳程序中不可用( while循环的父外壳).

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).

在文件本身中添加export命令:

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"

然后,您需要使用以下命令在当前Shell中获取文件的源代码:

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

. ./conf/prac1

OR

source ./conf/prac1

这篇关于从键/值对文件中设置环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆