Shell如何从.env文件设置环境变量

Jam*_*Lin 9 shell

假设我有.env文件包含如下行:

USERNAME=ABC
PASSWORD=PASS
Run Code Online (Sandbox Code Playgroud)

与普通的export前缀不同,所以我无法直接获取文件.

创建从.env文件加载内容并将其设置为环境变量的shell脚本的最简单方法是什么?

Cha*_*ffy 17

如果你的行是有效的,那么可信shell 不是export命令

这需要适当的shell引用.因此,如果你有一条像这样的线foo='bar baz',那就合适了,但是如果要写同一条线则不行foo=bar baz

set -a # automatically export all variables
source .env
set +a
Run Code Online (Sandbox Code Playgroud)

如果你的行不是有效的shell

下面读取键/值对,并不期望或尊重shell引用.

while IFS== read -r key value; do
  printf -v "$key" %s "$value" && export "$key"
done
Run Code Online (Sandbox Code Playgroud)

  • `source .env` 基本上可以满足需要。只需确保 .env 值中没有空格即可。 (2认同)
  • @AdépòjùOlúwáségun,如果没有“set -a”或“export”,则仅为本地 shell 设置值,而不为其子进程设置值。OP 明确表示“环境变量”,而不是“shell 变量”。`foo=bar` 不设置环境 shell 变量,它设置 shell 变量。 (2认同)

lut*_*uri 7

这个脚本非常适合我(2023 年 6 月)。

#!/bin/sh

# Load environment variables from .env file
[ ! -f .env ] || export $(grep -v '^#' .env | xargs)
Run Code Online (Sandbox Code Playgroud)

.env 文件示例:

# Database settings
DB_HOST=localhost
DB_PORT=5432
DB_NAME=mydatabase
DB_USER=myuser
DB_PASSWORD=mypassword

# API keys
API_KEY=abc123
SECRET_KEY=def456

# Other settings
DEBUG_MODE=true
LOG_LEVEL=info
Run Code Online (Sandbox Code Playgroud)


vou*_*rus 6

这将导出.env中的所有内容:

export $(xargs <.env)
Run Code Online (Sandbox Code Playgroud)

  • 考虑一下您的 `.env` 是否是使用以下代码创建的:`printf '%s\n' 'password="twowords"' 'another=foo' &gt;.env`。在这种情况下,传递给“export”的参数将是“password=two”、“words”和“another=foo”;“words”将不再是“password”的一部分,并且将是一个单独的参数(因此该命令将尝试导出名为“words”的预先存在的变量)。 (2认同)

kol*_*pto 5

这就是我使用的:

load_dotenv(){
  # https://stackoverflow.com/a/66118031/134904
  # Note: you might need to replace "\s" with "[[:space:]]"
  source <("$1" | sed -e '/^#/d;/^\s*$/d' -e "s/'/'\\\''/g" -e "s/=\(.*\)/='\1'/g")
}

set -a
[ -f "test.env" ] && load_dotenv "test.env"
set +a
Run Code Online (Sandbox Code Playgroud)

如果您正在使用direnv,请知道它已经支持.env开箱即用的文件:)

将其添加到您的.envrc

[ -f "test.env" ] && dotenv "test.env"
Run Code Online (Sandbox Code Playgroud)

direnv 的 stdlib 文档:https://direnv.net/man/direnv-stdlib.1.html