source 包含环境变量的文件,包括 bash 中的 "dash" 字符?

source a file containing environment variables including "dash" character in bash?

我正在使用 bash 并有一个名为 x.config 的文件,其中包含以下内容:

MY_VAR=Something1
ANOTHER=Something2

要将这些作为环境变量加载,我只使用 source:

$ source x.config

但是如果 MY_VAR 被调用 MY-VAR:

MY-VAR=Something1
ANOTHER=Something2

如果我做同样的事情,我会得到:

x.config:1: command not found: MY-VAR=Something1

我试过转义 - 和很多其他的东西,但我被卡住了。有人知道解决方法吗?

environment variable 中的破折号 (-) 不可移植,正如您所注意到的,会导致很多问题。您不能从 bash 设置这些。 修复您要调用的应用程序

也就是说,如果您无法更改目标应用程序,您可以从 python:

#!/usr/bin/python

import os

with open('x.config') as f:
    for line in f:
        name, value = line.strip().split('=')
        os.environ[name] = value

os.system('/path/to/your/app')

这是一个非常简单的配置 reader,对于更复杂的语法,您可能需要使用 ConfigParser

可能对您有用的纯 bash 解决方法是使用 env 重新 运行 脚本来设置环境。将此添加到脚本的开头。

if [[ ! -v myscript_env_set ]]; then
    export myscript_env_set=1
    readarray -t newenv < x.config
    exec env "${newenv[@]}" "[=10=]" "$@"
fi

# rest of the script here

这假定 x.config 除了变量赋值外不包含任何内容。如果 myscript_env_set 不在当前环境中,则将其放在那里以便下一次调用跳过此块。然后将赋值读入一个数组以传递给 env。使用 exec 将当前进程替换为另一个脚本调用,但使用环境中所需的变量。