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


为了记录在案,以下是问题的原始版本,并附有示例。

我在bash中写了一个脚本,它在某个文件夹中解析带有3个变量的文件,这是其中之一:

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

该文件的存放路径为。/conf/prac1

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

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

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

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

也许还有其他方法可以做到这一点,我只需要使用我传递的文件的环境变量作为脚本的参数。


当前回答

简单:

获取文件的内容 删除任何空行(以防你分开一些东西) 删除任何注释(以防你添加了一些…) 将export添加到所有行 对整个事件进行评估

eval (cat .env美元| sed - e / ^ $ / d - e / ^ # / d - e ' s / ^ /出口/ ')

另一个选择(你不必运行eval(感谢@Jaydeep)):

export $(cat .env | sed -e /^$/d -e /^#/d | xargs)

最后,如果你想让你的生活真的很简单,把这个添加到你的~/.bash_profile:

函数source_envfile() {export $(cat $1 | sed -e /^$/d -e /^#/d | xargs);}

(请务必重新加载bash设置!!~ /来源。bash_profile或. .只要新建一个标签/窗口,问题就解决了),你这样叫它:source_envfile .env

其他回答

t=$(mktemp) && export -p > "$t" && set -a && . ./.env && set +a && . "$t" && rm "$t" && unset t

它是如何工作的

Create temp file. Write all current environment variables values to the temp file. Enable exporting of all declared variables in the sources script to the environment. Read .env file. All variables will be exported into current environment. Disable exporting of all declared variables in the sources script to the environment. Read the contents of the temp file. Every line would have declare -x VAR="val" that would export each of the variables into environment. Remove temp file. Unset the variable holding temp file name.

特性

保留环境中已设置的变量的值 .env可以有注释 .env可以有空行 .env不像其他答案那样需要特殊的页眉或页脚(set -a和set +a) .env不需要对每个值都导出 一行程序

这是我的变种:

  with_env() {
    (set -a && . ./.env && "$@")
  }

与之前方案相比:

它不会泄漏作用域外的变量(来自.env的值不会暴露给调用者) 不clobber设置选项 返回已执行命令的退出代码 使用posix兼容的set -a 用途。而不是源,避免害羞 如果.env加载失败,则不会调用该命令

with_env rails console

SAVE=$(set +o | grep allexport) && set -o allexport && ..环境;评估“$SAVE”

这将保存/恢复您的原始选项,无论它们是什么。

使用set -o alleexport的优点是可以在没有正则表达式的情况下正确地跳过注释。

Set +o本身以bash稍后可以执行的格式输出所有当前选项。同样方便的是:set -o本身以人类友好的格式输出所有当前选项。

简单:

获取文件的内容 删除任何空行(以防你分开一些东西) 删除任何注释(以防你添加了一些…) 将export添加到所有行 对整个事件进行评估

eval (cat .env美元| sed - e / ^ $ / d - e / ^ # / d - e ' s / ^ /出口/ ')

另一个选择(你不必运行eval(感谢@Jaydeep)):

export $(cat .env | sed -e /^$/d -e /^#/d | xargs)

最后,如果你想让你的生活真的很简单,把这个添加到你的~/.bash_profile:

函数source_envfile() {export $(cat $1 | sed -e /^$/d -e /^#/d | xargs);}

(请务必重新加载bash设置!!~ /来源。bash_profile或. .只要新建一个标签/窗口,问题就解决了),你这样叫它:source_envfile .env

我找到的最短的方法是:

你的。env文件:

VARIABLE_NAME="A_VALUE"

那就

. ./.env && echo ${VARIABLE_NAME}

好处:因为它是一个简短的一行程序,所以在软件包中非常有用。json文件

  "scripts": {
    "echo:variable": ". ./.env && echo ${VARIABLE_NAME}"
  }