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,但同样的问题仍然适用

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


当前回答

我找到的最短的方法是:

你的。env文件:

VARIABLE_NAME="A_VALUE"

那就

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

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

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

其他回答

最佳和简单的解决方案 环境文件env.txt

fruit=apple
vegetable=carrot

代码文件Code .sh

#!/bin/bash

source <filepath>/env.txt
echo $fruit
echo $vegetable

值中的空格

这里有很多很好的答案,但我发现它们都缺乏对值中空白的支持:

DATABASE_CLIENT_HOST=host db-name db-user 0.0.0.0/0 md5

我发现了2个解决方案,这些值支持空行和注释。

一个基于sed和@javier-buzzi的答案:

source <(sed -e /^$/d -e /^#/d -e 's/.*/declare -x "&"/g' .env)

和一个读行在循环基于@john1024答案

while read -r line; do declare -x "$line"; done < <(egrep -v "(^#|^\s|^$)" .env)

这里的关键是使用声明-x并将line放在双引号中。我不知道为什么,但当你将循环代码重新格式化为多行时,它不会工作-我不是bash程序员,我只是狼吞虎咽地把这些放在一起,它对我来说仍然是魔法:)

最后,我提出了一个基于allexport + source的解决方案。这里的主要思想是防止重写现有变量。

function load_env_file() {
    local FILE_PATH="${1}"
    local EXISTENT_VARS=$(declare)

    set -o allexport
    source "${FILE_PATH}"
    set +o allexport

    # errors are supressed as "declare" returns also readonly vars which are not overridable
    eval "${EXISTENT_VARS}" 2> /dev/null || true
}

# Usage example:
load_env_file "path/to/.env"

在这里的几个其他答案中提到了alleexport选项,其中set -a是快捷方式。获取.env确实比遍历行和导出要好,因为它允许注释、空行,甚至命令生成的环境变量。我的.bashrc包含以下内容:

# .env loading in the shell
dotenv () {
  set -a
  [ -f .env ] && . .env
  set +a
}

# Run dotenv on login
dotenv

# Run dotenv on every new directory
cd () {
  builtin cd $@
  dotenv
}
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不需要对每个值都导出 一行程序