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

fruit=apple
vegetable=carrot

代码文件Code .sh

#!/bin/bash

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

其他回答

对于那些使用ruby的人,我制作了一个名为dotenv_export的小型实用工具gem。

使用

Dotenv_export是一个小的实用程序命令,它读取。env文件,并使用ruby dotenv实现将其转换为导出语句。

# first install `dotenv_export`
gem install dotenv_export

然后,在你的.bash_profile中,或者任何你想要加载环境变量的shell环境中,执行以下命令:

eval "$(dotenv-export /path/to/.env)"

我在Mac上使用docker-compose和.env文件,并想将.env导入到我的bash shell中(用于测试),这里的“最佳”答案是在以下变量上出错:

.env

NODE_ARGS=--expose-gc --max_old_space_size=2048

解决方案

所以我最终使用eval,并将env var defs包装在单引号中。

eval $(grep -v -e '^#' .env | xargs -I {} echo export \'{}\')

Bash的版本

$ /bin/bash --version
GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin18)
Copyright (C) 2007 Free Software Foundation, Inc.

一种zsh方法是在运行中创建一个文件,在每一行的开头都有导出,在subshell中来源它,并执行你的命令:

$ cat env.db
VAR=" value = with!! special chars #"
$ ( . =(sed 's/^[^#]/export \0/' < env.db) && echo $VAR) 
 value = with!! special chars #
$ echo $VAR

$
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不需要对每个值都导出 一行程序

我对此的贡献是对@的答案的扩展 User4040650允许在git repo中轻松使用。它将尝试从当前目录中获取。env文件,如果不存在,则从你所在的git repo中获取。env文件。如果你已经cd到子目录中,那么就不需要源../../,这是很有帮助的。环境之类的。

我把它放在我的.bashrc中,所以我只需要在需要的地方调用setenv

setenv() {
  local env_path
  if { [ -f .env ] && env_path='.env'; } || { env_path=$(git  rev-parse --show-toplevel 2>/dev/null)/.env && [ -f "$env_path" ]; }; then
    echo "sourcing $env_path"
    set -o allexport
    source "$env_path"
    set +o allexport
  else
    echo "No env file found"
  fi
}