在最简单的形式中,您可以将键值对加载到bash 数组中,如下所示:
IFS=$'\n' read -d '' -ra nameValuePairs < ./development.env
在 Bash v4+ 中,它更加简单:
readarray -t nameValuePairs < ./development.env
然后您可以将生成的"${nameValuePairs[@]}" 数组传递给export 或heroku config:set ... 等命令;例如:
export "${nameValuePairs[@]}"
但是请注意,只有当输入 *.env 文件满足以下条件中的所有时,上述内容才能按预期工作:
- 键是语法上有效的 shell 变量名,行格式为
<key>=<value>,= 周围没有空格
- 这些行不包含引号,也不包含前导或尾随空格
- 文件中没有空行/空行或注释行。
- 每个值都限制在一行中。
对于不符合这种严格格式的文件,需要采用不同的方法;例如,this related question 处理可能包含引用值的文件。
以下是名为load_env 的bash 脚本的源代码(.sh 后缀通常不是必需的且不明确):
您可以使用感兴趣的*.env 文件调用它,它会根据文件名 执行适当的操作(运行heroku config:set … 或export)。
但是,如上所述,您必须 source 脚本(使用 source 或其有效的 bash 别名,.)才能创建环境变量 (export ) 对 当前 shell 可见。
为防止隐晦的失败,如果您传递了 development.env 文件并且在没有源代码的情况下调用了脚本,脚本会报错。
例子:
./load_env ./staging.dev
. ./load_env ./development.dev # !! Note the need to source
load_env源代码
#!/usr/bin/env bash
# Helper function that keeps its aux. variables localized.
# Note that the function itself remains defined after sourced invocation, however.
configOrExport() {
local envFile=$1 doConfig=0 doExport=0 appName
case "$(basename "$envFile" '.env')" in
staging)
doConfig=1
# Set the desired app name here.
appName=stagingapp
;;
production)
doConfig=1
# Set the desired app name here.
appName=productionapp
;;
development)
doExport=1
;;
*)
echo "ERROR: Invalid or missing *.env file name: $(basename "$envFile" '.env')" >&2; exit 2
esac
# Make sure the file exists and is readable.
[[ -r "$envFile" ]] || { echo "ERROR: *.env file not found or not readable: $envFile" >&2; exit 2; }
# If variables must be exported, make sure the script is being sourced.
[[ $doExport -eq 1 && $0 == "$BASH_SOURCE" ]] && { echo "ERROR: To define environment variables, you must *source* this script." >&2; exit 2; }
# Read all key-value pairs from the *.env file into an array.
# Note: This assumes that:
# - the keys are syntactically valid shell variable names
# - the lines contain no quoting and no leading or trailing whitespace
# - there are no empty/blank lines or comment lines in the file.
IFS=$'\n' read -d '' -ra nameValuePairs < "$envFile"
# Run configuration command.
(( doConfig )) && { heroku config:set -a "$appName" "${nameValuePairs[@]}" || exit; }
# Export variables (define as environment variables).
(( doExport )) && { export "${nameValuePairs[@]}" || exit; }
}
# Invoke the helper function.
configOrExport "$@"